GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: lib/geogram_gfx/third_party/imgui/imgui.cpp Lines: 0 10203 0.0 %
Date: 2022-12-10 04:31:04 Branches: 0 12126 0.0 %

Line Branch Exec Source
1
// dear imgui, v1.90 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - Read FAQ at http://dearimgui.org/faq
6
// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
7
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
8
// Read imgui.cpp for details, links and comments.
9
10
// Resources:
11
// - FAQ                   http://dearimgui.org/faq
12
// - Homepage & latest     https://github.com/ocornut/imgui
13
// - Releases & changelog  https://github.com/ocornut/imgui/releases
14
// - Gallery               https://github.com/ocornut/imgui/issues/5243 (please post your screenshots/video there!)
15
// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16
// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
17
// - Issues & support      https://github.com/ocornut/imgui/issues
18
19
// Getting Started?
20
// - For first-time users having issues compiling/linking/running or issues loading fonts:
21
//   please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22
23
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
24
// See LICENSE.txt for copyright and licensing details (standard MIT License).
25
// This library is free but needs your support to sustain development and maintenance.
26
// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
27
// Individuals: you can support continued development via donations. See docs/README or web page.
28
29
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
30
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
31
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
32
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
33
// to a better solution or official support for them.
34
35
/*
36
37
Index of this file:
38
39
DOCUMENTATION
40
41
- MISSION STATEMENT
42
- END-USER GUIDE
43
- PROGRAMMER GUIDE
44
  - READ FIRST
45
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
46
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
47
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
48
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
49
  - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
50
- API BREAKING CHANGES (read me when you update!)
51
- FREQUENTLY ASKED QUESTIONS (FAQ)
52
  - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
53
54
CODE
55
(search for "[SECTION]" in the code to find them)
56
57
// [SECTION] INCLUDES
58
// [SECTION] FORWARD DECLARATIONS
59
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
60
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
61
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
62
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
63
// [SECTION] MISC HELPERS/UTILITIES (File functions)
64
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
65
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
66
// [SECTION] ImGuiStorage
67
// [SECTION] ImGuiTextFilter
68
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
69
// [SECTION] ImGuiListClipper
70
// [SECTION] STYLING
71
// [SECTION] RENDER HELPERS
72
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
73
// [SECTION] INPUTS
74
// [SECTION] ERROR CHECKING
75
// [SECTION] LAYOUT
76
// [SECTION] SCROLLING
77
// [SECTION] TOOLTIPS
78
// [SECTION] POPUPS
79
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
80
// [SECTION] DRAG AND DROP
81
// [SECTION] LOGGING/CAPTURING
82
// [SECTION] SETTINGS
83
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
84
// [SECTION] DOCKING
85
// [SECTION] PLATFORM DEPENDENT HELPERS
86
// [SECTION] METRICS/DEBUGGER WINDOW
87
// [SECTION] DEBUG LOG WINDOW
88
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
89
90
*/
91
92
//-----------------------------------------------------------------------------
93
// DOCUMENTATION
94
//-----------------------------------------------------------------------------
95
96
/*
97
98
 MISSION STATEMENT
99
 =================
100
101
 - Easy to use to create code-driven and data-driven tools.
102
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
103
 - Easy to hack and improve.
104
 - Minimize setup and maintenance.
105
 - Minimize state storage on user side.
106
 - Minimize state synchronization.
107
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
108
 - Efficient runtime and memory consumption.
109
110
 Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
111
112
 - Doesn't look fancy, doesn't animate.
113
 - Limited layout features, intricate layouts are typically crafted in code.
114
115
116
 END-USER GUIDE
117
 ==============
118
119
 - Double-click on title bar to collapse window.
120
 - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
121
 - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
122
 - Click and drag on any empty space to move window.
123
 - TAB/SHIFT+TAB to cycle through keyboard editable fields.
124
 - CTRL+Click on a slider or drag box to input value as text.
125
 - Use mouse wheel to scroll.
126
 - Text editor:
127
   - Hold SHIFT or use mouse to select text.
128
   - CTRL+Left/Right to word jump.
129
   - CTRL+Shift+Left/Right to select words.
130
   - CTRL+A or Double-Click to select all.
131
   - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
132
   - CTRL+Z,CTRL+Y to undo/redo.
133
   - ESCAPE to revert text to its original value.
134
   - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
135
 - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
136
 - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. Download controller mapping PNG/PSD at http://dearimgui.org/controls_sheets
137
138
139
 PROGRAMMER GUIDE
140
 ================
141
142
 READ FIRST
143
 ----------
144
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
145
 - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or
146
   destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
147
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
148
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
149
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
150
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
151
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
152
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
153
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
154
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
155
 - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
156
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
157
   If you get an assert, read the messages and comments around the assert.
158
 - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
159
 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
160
   See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
161
   However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
162
 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
163
164
165
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
166
 ----------------------------------------------
167
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
168
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
169
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
170
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
171
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
172
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
173
   likely be a comment about it. Please report any issue to the GitHub page!
174
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
175
 - Try to keep your copy of Dear ImGui reasonably up to date.
176
177
178
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
179
 ---------------------------------------------------------------
180
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
181
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
182
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
183
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
184
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
185
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
186
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
187
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
188
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
189
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
190
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
191
192
193
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
194
 --------------------------------------
195
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
196
 The sub-folders in examples/ contain examples applications following this structure.
197
198
     // Application init: create a dear imgui context, setup some options, load fonts
199
     ImGui::CreateContext();
200
     ImGuiIO& io = ImGui::GetIO();
201
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
202
     // TODO: Fill optional fields of the io structure later.
203
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
204
205
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
206
     ImGui_ImplWin32_Init(hwnd);
207
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
208
209
     // Application main loop
210
     while (true)
211
     {
212
         // Feed inputs to dear imgui, start new frame
213
         ImGui_ImplDX11_NewFrame();
214
         ImGui_ImplWin32_NewFrame();
215
         ImGui::NewFrame();
216
217
         // Any application code here
218
         ImGui::Text("Hello, world!");
219
220
         // Render dear imgui into screen
221
         ImGui::Render();
222
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
223
         g_pSwapChain->Present(1, 0);
224
     }
225
226
     // Shutdown
227
     ImGui_ImplDX11_Shutdown();
228
     ImGui_ImplWin32_Shutdown();
229
     ImGui::DestroyContext();
230
231
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
232
233
     // Application init: create a dear imgui context, setup some options, load fonts
234
     ImGui::CreateContext();
235
     ImGuiIO& io = ImGui::GetIO();
236
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
237
     // TODO: Fill optional fields of the io structure later.
238
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
239
240
     // Build and load the texture atlas into a texture
241
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
242
     int width, height;
243
     unsigned char* pixels = NULL;
244
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
245
246
     // At this point you've got the texture data and you need to upload that to your graphic system:
247
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
248
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
249
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
250
     io.Fonts->SetTexID((void*)texture);
251
252
     // Application main loop
253
     while (true)
254
     {
255
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
256
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
257
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
258
        io.DisplaySize.x = 1920.0f;             // set the current display width
259
        io.DisplaySize.y = 1280.0f;             // set the current display height here
260
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
261
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
262
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
263
264
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
265
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
266
        ImGui::NewFrame();
267
268
        // Most of your application code here
269
        ImGui::Text("Hello, world!");
270
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
271
        MyGameRender(); // may use any Dear ImGui functions as well!
272
273
        // Render dear imgui, swap buffers
274
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
275
        ImGui::EndFrame();
276
        ImGui::Render();
277
        ImDrawData* draw_data = ImGui::GetDrawData();
278
        MyImGuiRenderFunction(draw_data);
279
        SwapBuffers();
280
     }
281
282
     // Shutdown
283
     ImGui::DestroyContext();
284
285
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
286
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
287
 Please read the FAQ and example applications for details about this!
288
289
290
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
291
 ---------------------------------------------
292
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
293
294
    void MyImGuiRenderFunction(ImDrawData* draw_data)
295
    {
296
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
297
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
298
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
299
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
300
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
301
       ImVec2 clip_off = draw_data->DisplayPos;
302
       for (int n = 0; n < draw_data->CmdListsCount; n++)
303
       {
304
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
305
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
306
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
307
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
308
          {
309
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
310
             if (pcmd->UserCallback)
311
             {
312
                 pcmd->UserCallback(cmd_list, pcmd);
313
             }
314
             else
315
             {
316
                 // Project scissor/clipping rectangles into framebuffer space
317
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
318
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
319
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
320
                     continue;
321
322
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
323
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
324
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
325
                 // - Clipping coordinates are provided in imgui coordinates space:
326
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
327
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
328
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
329
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
330
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
331
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
332
333
                 // The texture for the draw call is specified by pcmd->GetTexID().
334
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
335
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
336
337
                 // Render 'pcmd->ElemCount/3' indexed triangles.
338
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
339
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
340
             }
341
          }
342
       }
343
    }
344
345
346
 USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
347
 ------------------------------------------
348
 - The gamepad/keyboard navigation is fairly functional and keeps being improved.
349
 - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
350
 - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
351
 - Keyboard:
352
    - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
353
    - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard),
354
      the io.WantCaptureKeyboard flag will be set. For more advanced uses, you may want to read from:
355
       - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
356
       - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
357
       - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
358
      Please reach out if you think the game vs navigation input sharing could be improved.
359
 - Gamepad:
360
    - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
361
    - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
362
      For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
363
      Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
364
    - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
365
    - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://dearimgui.org/controls_sheets
366
    - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
367
      with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
368
 - Mouse:
369
    - PS4/PS5 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
370
    - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
371
    - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
372
      Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
373
      When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
374
      When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
375
      (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse moving back and forth!)
376
      (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
377
       to set a boolean to ignore your other external mouse positions until the external source is moved again.)
378
379
380
 API BREAKING CHANGES
381
 ====================
382
383
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
384
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
385
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
386
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
387
388
(Docking/Viewport Branch)
389
 - 2022/XX/XX (1.XX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
390
                        - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
391
                          you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
392
                        - likewise io.MousePos and GetMousePos() will use OS coordinates.
393
                          If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
394
395
 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
396
 - 2022/10/12 (1.89) - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
397
 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
398
                         - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
399
                         - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
400
                         - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
401
                         - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
402
                       the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
403
                       the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
404
                       exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
405
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
406
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
407
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
408
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
409
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
410
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
411
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
412
                         - previously this would make the window content size ~200x200:
413
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
414
                         - instead, please submit an item:
415
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
416
                         - alternative:
417
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
418
                         - content size is now only extended when submitting an item!
419
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
420
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
421
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
422
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
423
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
424
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
425
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
426
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
427
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
428
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
429
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
430
                        - Official backends from 1.87+                  -> no issue.
431
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
432
                        - Custom backends not writing to io.NavInputs[] -> no issue.
433
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
434
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
435
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
436
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
437
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
438
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
439
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
440
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
441
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
442
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
443
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
444
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
445
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
446
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
447
                       read https://github.com/ocornut/imgui/issues/4921 for details.
448
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
449
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
450
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
451
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
452
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
453
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
454
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
455
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
456
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
457
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
458
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
459
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
460
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
461
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
462
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
463
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
464
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
465
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
466
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
467
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
468
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
469
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
470
                        - if you are using official backends from the source tree: you have nothing to do.
471
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
472
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
473
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
474
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
475
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
476
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
477
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
478
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
479
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
480
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
481
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
482
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
483
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
484
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
485
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
486
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
487
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
488
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
489
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
490
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
491
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
492
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
493
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
494
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
495
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
496
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
497
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
498
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
499
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
500
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
501
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
502
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
503
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
504
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
505
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
506
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
507
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
508
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
509
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
510
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
511
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
512
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
513
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
514
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
515
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
516
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
517
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
518
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
519
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
520
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
521
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
522
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
523
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
524
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
525
                       - if you omitted the 'power' parameter (likely!), you are not affected.
526
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
527
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
528
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
529
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
530
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
531
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
532
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
533
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
534
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
535
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
536
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
537
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
538
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
539
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
540
                       - ShowTestWindow()                    -> use ShowDemoWindow()
541
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
542
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
543
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
544
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
545
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
546
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
547
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
548
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
549
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
550
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
551
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
552
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
553
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
554
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
555
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
556
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
557
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
558
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
559
                       - ImFont::Glyph                       -> use ImFontGlyph
560
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
561
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
562
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
563
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
564
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
565
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
566
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
567
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
568
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
569
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
570
                       Please reach out if you are affected.
571
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
572
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
573
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
574
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
575
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
576
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
577
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
578
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
579
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
580
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
581
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
582
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
583
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
584
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
585
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
586
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
587
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
588
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
589
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
590
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
591
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
592
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
593
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
594
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
595
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
596
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
597
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
598
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
599
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
600
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
601
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
602
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
603
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
604
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
605
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
606
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
607
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
608
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
609
                       consistent with other functions. Kept redirection functions (will obsolete).
610
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
611
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
612
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
613
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
614
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
615
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
616
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
617
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
618
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
619
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
620
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
621
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
622
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
623
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
624
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
625
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
626
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
627
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
628
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
629
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
630
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
631
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
632
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
633
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
634
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
635
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
636
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
637
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
638
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
639
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
640
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
641
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
642
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
643
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
644
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
645
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
646
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
647
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
648
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
649
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
650
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
651
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
652
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
653
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
654
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
655
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
656
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
657
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
658
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
659
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
660
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
661
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
662
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
663
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
664
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
665
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
666
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
667
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
668
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
669
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
670
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
671
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
672
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
673
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
674
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
675
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
676
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
677
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
678
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
679
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
680
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
681
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
682
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
683
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
684
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
685
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
686
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
687
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
688
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
689
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
690
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
691
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
692
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
693
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
694
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
695
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
696
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
697
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
698
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
699
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
700
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
701
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
702
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
703
                     - the signature of the io.RenderDrawListsFn handler has changed!
704
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
705
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
706
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
707
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
708
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
709
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
710
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
711
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
712
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
713
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
714
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
715
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
716
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
717
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
718
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
719
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
720
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
721
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
722
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
723
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
724
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
725
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
726
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
727
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
728
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
729
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
730
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
731
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
732
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
733
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
734
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
735
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
736
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
737
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
738
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
739
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
740
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
741
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
742
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
743
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
744
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
745
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
746
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
747
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
748
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
749
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
750
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
751
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
752
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
753
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
754
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
755
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
756
757
758
 FREQUENTLY ASKED QUESTIONS (FAQ)
759
 ================================
760
761
 Read all answers online:
762
   https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
763
 Read all answers locally (with a text editor or ideally a Markdown viewer):
764
   docs/FAQ.md
765
 Some answers are copied down here to facilitate searching in code.
766
767
 Q&A: Basics
768
 ===========
769
770
 Q: Where is the documentation?
771
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
772
    - Run the examples/ and explore them.
773
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
774
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
775
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
776
    - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
777
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
778
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
779
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
780
    - Your programming IDE is your friend, find the type or function declaration to find comments
781
      associated with it.
782
783
 Q: What is this library called?
784
 Q: Which version should I get?
785
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
786
 >> See https://www.dearimgui.org/faq for details.
787
788
 Q&A: Integration
789
 ================
790
791
 Q: How to get started?
792
 A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
793
794
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
795
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
796
 >> See https://www.dearimgui.org/faq for a fully detailed answer. You really want to read this.
797
798
 Q. How can I enable keyboard controls?
799
 Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
800
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
801
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
802
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
803
 >> See https://www.dearimgui.org/faq
804
805
 Q&A: Usage
806
 ----------
807
808
 Q: About the ID Stack system..
809
   - Why is my widget not reacting when I click on it?
810
   - How can I have widgets with an empty label?
811
   - How can I have multiple widgets with the same label?
812
   - How can I have multiple windows with the same label?
813
 Q: How can I display an image? What is ImTextureID, how does it work?
814
 Q: How can I use my own math types instead of ImVec2/ImVec4?
815
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
816
 Q: How can I display custom shapes? (using low-level ImDrawList API)
817
 >> See https://www.dearimgui.org/faq
818
819
 Q&A: Fonts, Text
820
 ================
821
822
 Q: How should I handle DPI in my application?
823
 Q: How can I load a different font than the default?
824
 Q: How can I easily use icons in my application?
825
 Q: How can I load multiple fonts?
826
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
827
 >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
828
829
 Q&A: Concerns
830
 =============
831
832
 Q: Who uses Dear ImGui?
833
 Q: Can you create elaborate/serious tools with Dear ImGui?
834
 Q: Can you reskin the look of Dear ImGui?
835
 Q: Why using C++ (as opposed to C)?
836
 >> See https://www.dearimgui.org/faq
837
838
 Q&A: Community
839
 ==============
840
841
 Q: How can I help?
842
 A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
843
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
844
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.
845
    - Individuals: you can support continued development via PayPal donations. See README.
846
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
847
      and see how you want to help and can help!
848
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
849
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
850
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
851
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
852
853
*/
854
855
//-------------------------------------------------------------------------
856
// [SECTION] INCLUDES
857
//-------------------------------------------------------------------------
858
859
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
860
#define _CRT_SECURE_NO_WARNINGS
861
#endif
862
863
#include "imgui.h"
864
#ifndef IMGUI_DISABLE
865
866
#ifndef IMGUI_DEFINE_MATH_OPERATORS
867
#define IMGUI_DEFINE_MATH_OPERATORS
868
#endif
869
#include "imgui_internal.h"
870
871
// System includes
872
#include <stdio.h>      // vsnprintf, sscanf, printf
873
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
874
#include <stddef.h>     // intptr_t
875
#else
876
#include <stdint.h>     // intptr_t
877
#endif
878
879
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
880
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
881
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
882
#endif
883
884
// [Windows] OS specific includes (optional)
885
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
886
#define IMGUI_DISABLE_WIN32_FUNCTIONS
887
#endif
888
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
889
#ifndef WIN32_LEAN_AND_MEAN
890
#define WIN32_LEAN_AND_MEAN
891
#endif
892
#ifndef NOMINMAX
893
#define NOMINMAX
894
#endif
895
#ifndef __MINGW32__
896
#include <Windows.h>        // _wfopen, OpenClipboard
897
#else
898
#include <windows.h>
899
#endif
900
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
901
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
902
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
903
#endif
904
#endif
905
906
// [Apple] OS specific includes
907
#if defined(__APPLE__)
908
#include <TargetConditionals.h>
909
#endif
910
911
// Visual Studio warnings
912
#ifdef _MSC_VER
913
#pragma warning (disable: 4127)             // condition expression is constant
914
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
915
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
916
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
917
#endif
918
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
919
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
920
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
921
#endif
922
923
// Clang/GCC warnings with -Weverything
924
#if defined(__clang__)
925
#if __has_warning("-Wunknown-warning-option")
926
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
927
#endif
928
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
929
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
930
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
931
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
932
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
933
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
934
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
935
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
936
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
937
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
938
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
939
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
940
#elif defined(__GNUC__)
941
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
942
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
943
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
944
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
945
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
946
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
947
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
948
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
949
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
950
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
951
#endif
952
953
// Debug options
954
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
955
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
956
#define IMGUI_DEBUG_INI_SETTINGS    0   // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
957
958
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
959
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
960
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
961
962
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
963
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
964
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
965
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
966
967
// Docking
968
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
969
static const float DOCKING_SPLITTER_SIZE                    = 2.0f;
970
971
//-------------------------------------------------------------------------
972
// [SECTION] FORWARD DECLARATIONS
973
//-------------------------------------------------------------------------
974
975
static void             SetCurrentWindow(ImGuiWindow* window);
976
static void             FindHoveredWindow();
977
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
978
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
979
980
static void             AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
981
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
982
983
// Settings
984
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
985
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
986
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
987
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
988
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
989
990
// Platform Dependents default implementation for IO functions
991
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data);
992
static void             SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
993
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
994
995
namespace ImGui
996
{
997
// Navigation
998
static void             NavUpdate();
999
static void             NavUpdateWindowing();
1000
static void             NavUpdateWindowingOverlay();
1001
static void             NavUpdateCancelRequest();
1002
static void             NavUpdateCreateMoveRequest();
1003
static void             NavUpdateCreateTabbingRequest();
1004
static float            NavUpdatePageUpPageDown();
1005
static inline void      NavUpdateAnyRequestFlag();
1006
static void             NavUpdateCreateWrappingRequest();
1007
static void             NavEndFrame();
1008
static bool             NavScoreItem(ImGuiNavItemData* result);
1009
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1010
static void             NavProcessItem();
1011
static void             NavProcessItemForTabbingRequest(ImGuiID id);
1012
static ImVec2           NavCalcPreferredRefPos();
1013
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1014
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1015
static void             NavRestoreLayer(ImGuiNavLayer layer);
1016
static void             NavRestoreHighlightAfterMove();
1017
static int              FindWindowFocusIndex(ImGuiWindow* window);
1018
1019
// Error Checking and Debug Tools
1020
static void             ErrorCheckNewFrameSanityChecks();
1021
static void             ErrorCheckEndFrameSanityChecks();
1022
static void             UpdateDebugToolItemPicker();
1023
static void             UpdateDebugToolStackQueries();
1024
1025
// Misc
1026
static void             UpdateSettings();
1027
static void             UpdateKeyboardInputs();
1028
static void             UpdateMouseInputs();
1029
static void             UpdateMouseWheel();
1030
static bool             UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1031
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1032
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1033
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1034
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1035
static void             RenderDimmedBackgrounds();
1036
static ImGuiWindow*     FindBlockingModal(ImGuiWindow* window);
1037
1038
// Viewports
1039
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1040
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1041
static void             DestroyViewport(ImGuiViewportP* viewport);
1042
static void             UpdateViewportsNewFrame();
1043
static void             UpdateViewportsEndFrame();
1044
static void             WindowSelectViewport(ImGuiWindow* window);
1045
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1046
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1047
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1048
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1049
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1050
static int              FindPlatformMonitorForRect(const ImRect& r);
1051
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1052
1053
}
1054
1055
//-----------------------------------------------------------------------------
1056
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1057
//-----------------------------------------------------------------------------
1058
1059
// DLL users:
1060
// - Heaps and globals are not shared across DLL boundaries!
1061
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1062
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1063
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1064
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1065
1066
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1067
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1068
//   Change to a different context by calling ImGui::SetCurrentContext().
1069
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1070
//   If you want thread-safety to allow N threads to access N different contexts:
1071
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1072
//         struct ImGuiContext;
1073
//         extern thread_local ImGuiContext* MyImGuiTLS;
1074
//         #define GImGui MyImGuiTLS
1075
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1076
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1077
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1078
// - DLL users: read comments above.
1079
#ifndef GImGui
1080
ImGuiContext*   GImGui = NULL;
1081
#endif
1082
1083
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1084
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1085
// - DLL users: read comments above.
1086
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1087
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1088
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1089
#else
1090
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1091
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1092
#endif
1093
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1094
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1095
static void*                GImAllocatorUserData = NULL;
1096
1097
//-----------------------------------------------------------------------------
1098
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1099
//-----------------------------------------------------------------------------
1100
1101
ImGuiStyle::ImGuiStyle()
1102
{
1103
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1104
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1105
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1106
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1107
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1108
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1109
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1110
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1111
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1112
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1113
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1114
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1115
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1116
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1117
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1118
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1119
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1120
    CellPadding             = ImVec2(4,2);      // Padding within a table cell
1121
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1122
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1123
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1124
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1125
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1126
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1127
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1128
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1129
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1130
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1131
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1132
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1133
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1134
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1135
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1136
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1137
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1138
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1139
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1140
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1141
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1142
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1143
1144
    // Default theme
1145
    ImGui::StyleColorsDark(this);
1146
}
1147
1148
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1149
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1150
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1151
{
1152
    WindowPadding = ImFloor(WindowPadding * scale_factor);
1153
    WindowRounding = ImFloor(WindowRounding * scale_factor);
1154
    WindowMinSize = ImFloor(WindowMinSize * scale_factor);
1155
    ChildRounding = ImFloor(ChildRounding * scale_factor);
1156
    PopupRounding = ImFloor(PopupRounding * scale_factor);
1157
    FramePadding = ImFloor(FramePadding * scale_factor);
1158
    FrameRounding = ImFloor(FrameRounding * scale_factor);
1159
    ItemSpacing = ImFloor(ItemSpacing * scale_factor);
1160
    ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
1161
    CellPadding = ImFloor(CellPadding * scale_factor);
1162
    TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
1163
    IndentSpacing = ImFloor(IndentSpacing * scale_factor);
1164
    ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
1165
    ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
1166
    ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
1167
    GrabMinSize = ImFloor(GrabMinSize * scale_factor);
1168
    GrabRounding = ImFloor(GrabRounding * scale_factor);
1169
    LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
1170
    TabRounding = ImFloor(TabRounding * scale_factor);
1171
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1172
    DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
1173
    DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
1174
    MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
1175
}
1176
1177
ImGuiIO::ImGuiIO()
1178
{
1179
    // Most fields are initialized with zero
1180
    memset(this, 0, sizeof(*this));
1181
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1182
1183
    // Settings
1184
    ConfigFlags = ImGuiConfigFlags_None;
1185
    BackendFlags = ImGuiBackendFlags_None;
1186
    DisplaySize = ImVec2(-1.0f, -1.0f);
1187
    DeltaTime = 1.0f / 60.0f;
1188
    IniSavingRate = 5.0f;
1189
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1190
    LogFilename = "imgui_log.txt";
1191
    MouseDoubleClickTime = 0.30f;
1192
    MouseDoubleClickMaxDist = 6.0f;
1193
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1194
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1195
        KeyMap[i] = -1;
1196
#endif
1197
    KeyRepeatDelay = 0.275f;
1198
    KeyRepeatRate = 0.050f;
1199
    HoverDelayNormal = 0.30f;
1200
    HoverDelayShort = 0.10f;
1201
    UserData = NULL;
1202
1203
    Fonts = NULL;
1204
    FontGlobalScale = 1.0f;
1205
    FontDefault = NULL;
1206
    FontAllowUserScaling = false;
1207
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1208
1209
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1210
    ConfigDockingNoSplit = false;
1211
    ConfigDockingWithShift = false;
1212
    ConfigDockingAlwaysTabBar = false;
1213
    ConfigDockingTransparentPayload = false;
1214
1215
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1216
    ConfigViewportsNoAutoMerge = false;
1217
    ConfigViewportsNoTaskBarIcon = false;
1218
    ConfigViewportsNoDecoration = true;
1219
    ConfigViewportsNoDefaultParent = false;
1220
1221
    // Miscellaneous options
1222
    MouseDrawCursor = false;
1223
#ifdef __APPLE__
1224
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1225
#else
1226
    ConfigMacOSXBehaviors = false;
1227
#endif
1228
    ConfigInputTrickleEventQueue = true;
1229
    ConfigInputTextCursorBlink = true;
1230
    ConfigInputTextEnterKeepActive = false;
1231
    ConfigDragClickToInputText = false;
1232
    ConfigWindowsResizeFromEdges = true;
1233
    ConfigWindowsMoveFromTitleBarOnly = false;
1234
    ConfigMemoryCompactTimer = 60.0f;
1235
1236
    // Platform Functions
1237
    BackendPlatformName = BackendRendererName = NULL;
1238
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1239
    GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;   // Platform dependent default implementations
1240
    SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
1241
    ClipboardUserData = NULL;
1242
    SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
1243
1244
    // Input (NB: we already have memset zero the entire structure!)
1245
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1246
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1247
    MouseDragThreshold = 6.0f;
1248
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1249
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1250
    AppAcceptingEvents = true;
1251
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1252
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1253
}
1254
1255
// Pass in translated ASCII characters for text input.
1256
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1257
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1258
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1259
void ImGuiIO::AddInputCharacter(unsigned int c)
1260
{
1261
    ImGuiContext& g = *GImGui;
1262
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1263
    if (c == 0 || !AppAcceptingEvents)
1264
        return;
1265
1266
    ImGuiInputEvent e;
1267
    e.Type = ImGuiInputEventType_Text;
1268
    e.Source = ImGuiInputSource_Keyboard;
1269
    e.Text.Char = c;
1270
    g.InputEventsQueue.push_back(e);
1271
}
1272
1273
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1274
// we should save the high surrogate.
1275
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1276
{
1277
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1278
        return;
1279
1280
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1281
    {
1282
        if (InputQueueSurrogate != 0)
1283
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1284
        InputQueueSurrogate = c;
1285
        return;
1286
    }
1287
1288
    ImWchar cp = c;
1289
    if (InputQueueSurrogate != 0)
1290
    {
1291
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1292
        {
1293
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1294
        }
1295
        else
1296
        {
1297
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1298
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1299
#else
1300
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1301
#endif
1302
        }
1303
1304
        InputQueueSurrogate = 0;
1305
    }
1306
    AddInputCharacter((unsigned)cp);
1307
}
1308
1309
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1310
{
1311
    if (!AppAcceptingEvents)
1312
        return;
1313
    while (*utf8_chars != 0)
1314
    {
1315
        unsigned int c = 0;
1316
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1317
        if (c != 0)
1318
            AddInputCharacter(c);
1319
    }
1320
}
1321
1322
// FIXME: Perhaps we could clear queued events as well?
1323
void ImGuiIO::ClearInputCharacters()
1324
{
1325
    InputQueueCharacters.resize(0);
1326
}
1327
1328
// FIXME: Perhaps we could clear queued events as well?
1329
void ImGuiIO::ClearInputKeys()
1330
{
1331
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1332
    memset(KeysDown, 0, sizeof(KeysDown));
1333
#endif
1334
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1335
    {
1336
        KeysData[n].Down             = false;
1337
        KeysData[n].DownDuration     = -1.0f;
1338
        KeysData[n].DownDurationPrev = -1.0f;
1339
    }
1340
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1341
    KeyMods = ImGuiMod_None;
1342
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1343
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1344
    {
1345
        MouseDown[n] = false;
1346
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1347
    }
1348
    MouseWheel = MouseWheelH = 0.0f;
1349
}
1350
1351
static ImGuiInputEvent* FindLatestInputEvent(ImGuiInputEventType type, int arg = -1)
1352
{
1353
    ImGuiContext& g = *GImGui;
1354
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1355
    {
1356
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1357
        if (e->Type != type)
1358
            continue;
1359
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1360
            continue;
1361
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1362
            continue;
1363
        return e;
1364
    }
1365
    return NULL;
1366
}
1367
1368
// Queue a new key down/up event.
1369
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1370
// - bool down:          Is the key down? use false to signify a key release.
1371
// - float analog_value: 0.0f..1.0f
1372
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1373
{
1374
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1375
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1376
        return;
1377
    ImGuiContext& g = *GImGui;
1378
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1379
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1380
    IM_ASSERT(!ImGui::IsAliasKey(key)); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1381
1382
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1383
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1384
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1385
    if (BackendUsingLegacyKeyArrays == -1)
1386
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1387
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1388
    BackendUsingLegacyKeyArrays = 0;
1389
#endif
1390
    if (ImGui::IsGamepadKey(key))
1391
        BackendUsingLegacyNavInputArray = false;
1392
1393
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1394
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_Key, (int)key);
1395
    const ImGuiKeyData* key_data = ImGui::GetKeyData(key);
1396
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1397
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1398
    if (latest_key_down == down && latest_key_analog == analog_value)
1399
        return;
1400
1401
    // Add event
1402
    ImGuiInputEvent e;
1403
    e.Type = ImGuiInputEventType_Key;
1404
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1405
    e.Key.Key = key;
1406
    e.Key.Down = down;
1407
    e.Key.AnalogValue = analog_value;
1408
    g.InputEventsQueue.push_back(e);
1409
}
1410
1411
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1412
{
1413
    if (!AppAcceptingEvents)
1414
        return;
1415
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1416
}
1417
1418
// [Optional] Call after AddKeyEvent().
1419
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1420
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1421
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1422
{
1423
    if (key == ImGuiKey_None)
1424
        return;
1425
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1426
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1427
    IM_UNUSED(native_keycode);  // Yet unused
1428
    IM_UNUSED(native_scancode); // Yet unused
1429
1430
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1431
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1432
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1433
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1434
        return;
1435
    KeyMap[legacy_key] = key;
1436
    KeyMap[key] = legacy_key;
1437
#else
1438
    IM_UNUSED(key);
1439
    IM_UNUSED(native_legacy_index);
1440
#endif
1441
}
1442
1443
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1444
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1445
{
1446
    AppAcceptingEvents = accepting_events;
1447
}
1448
1449
// Queue a mouse move event
1450
void ImGuiIO::AddMousePosEvent(float x, float y)
1451
{
1452
    ImGuiContext& g = *GImGui;
1453
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1454
    if (!AppAcceptingEvents)
1455
        return;
1456
1457
    // Apply same flooring as UpdateMouseInputs()
1458
    ImVec2 pos((x > -FLT_MAX) ? ImFloorSigned(x) : x, (y > -FLT_MAX) ? ImFloorSigned(y) : y);
1459
1460
    // Filter duplicate
1461
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MousePos);
1462
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1463
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1464
        return;
1465
1466
    ImGuiInputEvent e;
1467
    e.Type = ImGuiInputEventType_MousePos;
1468
    e.Source = ImGuiInputSource_Mouse;
1469
    e.MousePos.PosX = pos.x;
1470
    e.MousePos.PosY = pos.y;
1471
    g.InputEventsQueue.push_back(e);
1472
}
1473
1474
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1475
{
1476
    ImGuiContext& g = *GImGui;
1477
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1478
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1479
    if (!AppAcceptingEvents)
1480
        return;
1481
1482
    // Filter duplicate
1483
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MouseButton, (int)mouse_button);
1484
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1485
    if (latest_button_down == down)
1486
        return;
1487
1488
    ImGuiInputEvent e;
1489
    e.Type = ImGuiInputEventType_MouseButton;
1490
    e.Source = ImGuiInputSource_Mouse;
1491
    e.MouseButton.Button = mouse_button;
1492
    e.MouseButton.Down = down;
1493
    g.InputEventsQueue.push_back(e);
1494
}
1495
1496
// Queue a mouse wheel event (most mouse/API will only have a Y component)
1497
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1498
{
1499
    ImGuiContext& g = *GImGui;
1500
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1501
1502
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1503
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1504
        return;
1505
1506
    ImGuiInputEvent e;
1507
    e.Type = ImGuiInputEventType_MouseWheel;
1508
    e.Source = ImGuiInputSource_Mouse;
1509
    e.MouseWheel.WheelX = wheel_x;
1510
    e.MouseWheel.WheelY = wheel_y;
1511
    g.InputEventsQueue.push_back(e);
1512
}
1513
1514
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1515
{
1516
    ImGuiContext& g = *GImGui;
1517
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1518
    IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1519
    if (!AppAcceptingEvents)
1520
        return;
1521
1522
    // Filter duplicate
1523
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MouseViewport);
1524
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1525
    if (latest_viewport_id == viewport_id)
1526
        return;
1527
1528
    ImGuiInputEvent e;
1529
    e.Type = ImGuiInputEventType_MouseViewport;
1530
    e.Source = ImGuiInputSource_Mouse;
1531
    e.MouseViewport.HoveredViewportID = viewport_id;
1532
    g.InputEventsQueue.push_back(e);
1533
}
1534
1535
void ImGuiIO::AddFocusEvent(bool focused)
1536
{
1537
    ImGuiContext& g = *GImGui;
1538
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1539
1540
    // Filter duplicate
1541
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_Focus);
1542
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1543
    if (latest_focused == focused)
1544
        return;
1545
1546
    ImGuiInputEvent e;
1547
    e.Type = ImGuiInputEventType_Focus;
1548
    e.AppFocused.Focused = focused;
1549
    g.InputEventsQueue.push_back(e);
1550
}
1551
1552
//-----------------------------------------------------------------------------
1553
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1554
//-----------------------------------------------------------------------------
1555
1556
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1557
{
1558
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1559
    ImVec2 p_last = p1;
1560
    ImVec2 p_closest;
1561
    float p_closest_dist2 = FLT_MAX;
1562
    float t_step = 1.0f / (float)num_segments;
1563
    for (int i_step = 1; i_step <= num_segments; i_step++)
1564
    {
1565
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1566
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1567
        float dist2 = ImLengthSqr(p - p_line);
1568
        if (dist2 < p_closest_dist2)
1569
        {
1570
            p_closest = p_line;
1571
            p_closest_dist2 = dist2;
1572
        }
1573
        p_last = p_current;
1574
    }
1575
    return p_closest;
1576
}
1577
1578
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1579
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1580
{
1581
    float dx = x4 - x1;
1582
    float dy = y4 - y1;
1583
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1584
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1585
    d2 = (d2 >= 0) ? d2 : -d2;
1586
    d3 = (d3 >= 0) ? d3 : -d3;
1587
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1588
    {
1589
        ImVec2 p_current(x4, y4);
1590
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1591
        float dist2 = ImLengthSqr(p - p_line);
1592
        if (dist2 < p_closest_dist2)
1593
        {
1594
            p_closest = p_line;
1595
            p_closest_dist2 = dist2;
1596
        }
1597
        p_last = p_current;
1598
    }
1599
    else if (level < 10)
1600
    {
1601
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1602
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1603
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1604
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1605
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1606
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1607
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1608
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1609
    }
1610
}
1611
1612
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1613
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1614
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1615
{
1616
    IM_ASSERT(tess_tol > 0.0f);
1617
    ImVec2 p_last = p1;
1618
    ImVec2 p_closest;
1619
    float p_closest_dist2 = FLT_MAX;
1620
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1621
    return p_closest;
1622
}
1623
1624
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1625
{
1626
    ImVec2 ap = p - a;
1627
    ImVec2 ab_dir = b - a;
1628
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1629
    if (dot < 0.0f)
1630
        return a;
1631
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1632
    if (dot > ab_len_sqr)
1633
        return b;
1634
    return a + ab_dir * dot / ab_len_sqr;
1635
}
1636
1637
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1638
{
1639
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1640
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1641
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1642
    return ((b1 == b2) && (b2 == b3));
1643
}
1644
1645
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1646
{
1647
    ImVec2 v0 = b - a;
1648
    ImVec2 v1 = c - a;
1649
    ImVec2 v2 = p - a;
1650
    const float denom = v0.x * v1.y - v1.x * v0.y;
1651
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1652
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1653
    out_u = 1.0f - out_v - out_w;
1654
}
1655
1656
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1657
{
1658
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1659
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1660
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1661
    float dist2_ab = ImLengthSqr(p - proj_ab);
1662
    float dist2_bc = ImLengthSqr(p - proj_bc);
1663
    float dist2_ca = ImLengthSqr(p - proj_ca);
1664
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1665
    if (m == dist2_ab)
1666
        return proj_ab;
1667
    if (m == dist2_bc)
1668
        return proj_bc;
1669
    return proj_ca;
1670
}
1671
1672
//-----------------------------------------------------------------------------
1673
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1674
//-----------------------------------------------------------------------------
1675
1676
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1677
int ImStricmp(const char* str1, const char* str2)
1678
{
1679
    int d;
1680
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1681
    return d;
1682
}
1683
1684
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1685
{
1686
    int d = 0;
1687
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1688
    return d;
1689
}
1690
1691
void ImStrncpy(char* dst, const char* src, size_t count)
1692
{
1693
    if (count < 1)
1694
        return;
1695
    if (count > 1)
1696
        strncpy(dst, src, count - 1);
1697
    dst[count - 1] = 0;
1698
}
1699
1700
char* ImStrdup(const char* str)
1701
{
1702
    size_t len = strlen(str);
1703
    void* buf = IM_ALLOC(len + 1);
1704
    return (char*)memcpy(buf, (const void*)str, len + 1);
1705
}
1706
1707
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1708
{
1709
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1710
    size_t src_size = strlen(src) + 1;
1711
    if (dst_buf_size < src_size)
1712
    {
1713
        IM_FREE(dst);
1714
        dst = (char*)IM_ALLOC(src_size);
1715
        if (p_dst_size)
1716
            *p_dst_size = src_size;
1717
    }
1718
    return (char*)memcpy(dst, (const void*)src, src_size);
1719
}
1720
1721
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1722
{
1723
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1724
    return p;
1725
}
1726
1727
int ImStrlenW(const ImWchar* str)
1728
{
1729
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1730
    int n = 0;
1731
    while (*str++) n++;
1732
    return n;
1733
}
1734
1735
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1736
const char* ImStreolRange(const char* str, const char* str_end)
1737
{
1738
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1739
    return p ? p : str_end;
1740
}
1741
1742
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1743
{
1744
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1745
        buf_mid_line--;
1746
    return buf_mid_line;
1747
}
1748
1749
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1750
{
1751
    if (!needle_end)
1752
        needle_end = needle + strlen(needle);
1753
1754
    const char un0 = (char)ImToUpper(*needle);
1755
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1756
    {
1757
        if (ImToUpper(*haystack) == un0)
1758
        {
1759
            const char* b = needle + 1;
1760
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1761
                if (ImToUpper(*a) != ImToUpper(*b))
1762
                    break;
1763
            if (b == needle_end)
1764
                return haystack;
1765
        }
1766
        haystack++;
1767
    }
1768
    return NULL;
1769
}
1770
1771
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1772
void ImStrTrimBlanks(char* buf)
1773
{
1774
    char* p = buf;
1775
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1776
        p++;
1777
    char* p_start = p;
1778
    while (*p != 0)                         // Find end of string
1779
        p++;
1780
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1781
        p--;
1782
    if (p_start != buf)                     // Copy memory if we had leading blanks
1783
        memmove(buf, p_start, p - p_start);
1784
    buf[p - p_start] = 0;                   // Zero terminate
1785
}
1786
1787
const char* ImStrSkipBlank(const char* str)
1788
{
1789
    while (str[0] == ' ' || str[0] == '\t')
1790
        str++;
1791
    return str;
1792
}
1793
1794
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1795
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1796
// B) When buf==NULL vsnprintf() will return the output size.
1797
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1798
1799
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1800
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1801
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1802
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1803
#ifdef IMGUI_USE_STB_SPRINTF
1804
#define STB_SPRINTF_IMPLEMENTATION
1805
#ifdef IMGUI_STB_SPRINTF_FILENAME
1806
#include IMGUI_STB_SPRINTF_FILENAME
1807
#else
1808
#include "stb_sprintf.h"
1809
#endif
1810
#endif
1811
1812
#if defined(_MSC_VER) && !defined(vsnprintf)
1813
#define vsnprintf _vsnprintf
1814
#endif
1815
1816
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1817
{
1818
    va_list args;
1819
    va_start(args, fmt);
1820
#ifdef IMGUI_USE_STB_SPRINTF
1821
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1822
#else
1823
    int w = vsnprintf(buf, buf_size, fmt, args);
1824
#endif
1825
    va_end(args);
1826
    if (buf == NULL)
1827
        return w;
1828
    if (w == -1 || w >= (int)buf_size)
1829
        w = (int)buf_size - 1;
1830
    buf[w] = 0;
1831
    return w;
1832
}
1833
1834
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1835
{
1836
#ifdef IMGUI_USE_STB_SPRINTF
1837
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1838
#else
1839
    int w = vsnprintf(buf, buf_size, fmt, args);
1840
#endif
1841
    if (buf == NULL)
1842
        return w;
1843
    if (w == -1 || w >= (int)buf_size)
1844
        w = (int)buf_size - 1;
1845
    buf[w] = 0;
1846
    return w;
1847
}
1848
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1849
1850
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1851
{
1852
    ImGuiContext& g = *GImGui;
1853
    va_list args;
1854
    va_start(args, fmt);
1855
    int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1856
    *out_buf = g.TempBuffer.Data;
1857
    if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1858
    va_end(args);
1859
}
1860
1861
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
1862
{
1863
    ImGuiContext& g = *GImGui;
1864
    int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1865
    *out_buf = g.TempBuffer.Data;
1866
    if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1867
}
1868
1869
// CRC32 needs a 1KB lookup table (not cache friendly)
1870
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
1871
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
1872
static const ImU32 GCrc32LookupTable[256] =
1873
{
1874
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
1875
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
1876
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
1877
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
1878
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
1879
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
1880
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
1881
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
1882
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
1883
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
1884
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
1885
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
1886
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
1887
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
1888
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
1889
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
1890
};
1891
1892
// Known size hash
1893
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
1894
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1895
ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed)
1896
{
1897
    ImU32 crc = ~seed;
1898
    const unsigned char* data = (const unsigned char*)data_p;
1899
    const ImU32* crc32_lut = GCrc32LookupTable;
1900
    while (data_size-- != 0)
1901
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
1902
    return ~crc;
1903
}
1904
1905
// Zero-terminated string hash, with support for ### to reset back to seed value
1906
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
1907
// Because this syntax is rarely used we are optimizing for the common case.
1908
// - If we reach ### in the string we discard the hash so far and reset to the seed.
1909
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
1910
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1911
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
1912
{
1913
    seed = ~seed;
1914
    ImU32 crc = seed;
1915
    const unsigned char* data = (const unsigned char*)data_p;
1916
    const ImU32* crc32_lut = GCrc32LookupTable;
1917
    if (data_size != 0)
1918
    {
1919
        while (data_size-- != 0)
1920
        {
1921
            unsigned char c = *data++;
1922
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
1923
                crc = seed;
1924
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1925
        }
1926
    }
1927
    else
1928
    {
1929
        while (unsigned char c = *data++)
1930
        {
1931
            if (c == '#' && data[0] == '#' && data[1] == '#')
1932
                crc = seed;
1933
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1934
        }
1935
    }
1936
    return ~crc;
1937
}
1938
1939
//-----------------------------------------------------------------------------
1940
// [SECTION] MISC HELPERS/UTILITIES (File functions)
1941
//-----------------------------------------------------------------------------
1942
1943
// Default file functions
1944
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
1945
1946
ImFileHandle ImFileOpen(const char* filename, const char* mode)
1947
{
1948
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
1949
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
1950
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
1951
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
1952
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
1953
    ImVector<ImWchar> buf;
1954
    buf.resize(filename_wsize + mode_wsize);
1955
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
1956
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
1957
    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
1958
#else
1959
    return fopen(filename, mode);
1960
#endif
1961
}
1962
1963
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
1964
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
1965
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
1966
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
1967
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
1968
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
1969
1970
// Helper: Load file content into memory
1971
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
1972
// This can't really be used with "rt" because fseek size won't match read size.
1973
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
1974
{
1975
    IM_ASSERT(filename && mode);
1976
    if (out_file_size)
1977
        *out_file_size = 0;
1978
1979
    ImFileHandle f;
1980
    if ((f = ImFileOpen(filename, mode)) == NULL)
1981
        return NULL;
1982
1983
    size_t file_size = (size_t)ImFileGetSize(f);
1984
    if (file_size == (size_t)-1)
1985
    {
1986
        ImFileClose(f);
1987
        return NULL;
1988
    }
1989
1990
    void* file_data = IM_ALLOC(file_size + padding_bytes);
1991
    if (file_data == NULL)
1992
    {
1993
        ImFileClose(f);
1994
        return NULL;
1995
    }
1996
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
1997
    {
1998
        ImFileClose(f);
1999
        IM_FREE(file_data);
2000
        return NULL;
2001
    }
2002
    if (padding_bytes > 0)
2003
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2004
2005
    ImFileClose(f);
2006
    if (out_file_size)
2007
        *out_file_size = file_size;
2008
2009
    return file_data;
2010
}
2011
2012
//-----------------------------------------------------------------------------
2013
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2014
//-----------------------------------------------------------------------------
2015
2016
// Convert UTF-8 to 32-bit character, process single character input.
2017
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2018
// We handle UTF-8 decoding error by skipping forward.
2019
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2020
{
2021
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2022
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2023
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2024
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2025
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2026
    int len = lengths[*(const unsigned char*)in_text >> 3];
2027
    int wanted = len + !len;
2028
2029
    if (in_text_end == NULL)
2030
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2031
2032
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2033
    // so it is fast even with excessive branching.
2034
    unsigned char s[4];
2035
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2036
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2037
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2038
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2039
2040
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2041
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2042
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2043
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2044
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2045
    *out_char >>= shiftc[len];
2046
2047
    // Accumulate the various error conditions.
2048
    int e = 0;
2049
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2050
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2051
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2052
    e |= (s[1] & 0xc0) >> 2;
2053
    e |= (s[2] & 0xc0) >> 4;
2054
    e |= (s[3]       ) >> 6;
2055
    e ^= 0x2a; // top two bits of each tail byte correct?
2056
    e >>= shifte[len];
2057
2058
    if (e)
2059
    {
2060
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2061
        // One byte is consumed in case of invalid first byte of in_text.
2062
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2063
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2064
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2065
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2066
    }
2067
2068
    return wanted;
2069
}
2070
2071
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2072
{
2073
    ImWchar* buf_out = buf;
2074
    ImWchar* buf_end = buf + buf_size;
2075
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2076
    {
2077
        unsigned int c;
2078
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2079
        if (c == 0)
2080
            break;
2081
        *buf_out++ = (ImWchar)c;
2082
    }
2083
    *buf_out = 0;
2084
    if (in_text_remaining)
2085
        *in_text_remaining = in_text;
2086
    return (int)(buf_out - buf);
2087
}
2088
2089
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2090
{
2091
    int char_count = 0;
2092
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2093
    {
2094
        unsigned int c;
2095
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2096
        if (c == 0)
2097
            break;
2098
        char_count++;
2099
    }
2100
    return char_count;
2101
}
2102
2103
// Based on stb_to_utf8() from github.com/nothings/stb/
2104
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2105
{
2106
    if (c < 0x80)
2107
    {
2108
        buf[0] = (char)c;
2109
        return 1;
2110
    }
2111
    if (c < 0x800)
2112
    {
2113
        if (buf_size < 2) return 0;
2114
        buf[0] = (char)(0xc0 + (c >> 6));
2115
        buf[1] = (char)(0x80 + (c & 0x3f));
2116
        return 2;
2117
    }
2118
    if (c < 0x10000)
2119
    {
2120
        if (buf_size < 3) return 0;
2121
        buf[0] = (char)(0xe0 + (c >> 12));
2122
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2123
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2124
        return 3;
2125
    }
2126
    if (c <= 0x10FFFF)
2127
    {
2128
        if (buf_size < 4) return 0;
2129
        buf[0] = (char)(0xf0 + (c >> 18));
2130
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2131
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2132
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2133
        return 4;
2134
    }
2135
    // Invalid code point, the max unicode is 0x10FFFF
2136
    return 0;
2137
}
2138
2139
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2140
{
2141
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2142
    out_buf[count] = 0;
2143
    return out_buf;
2144
}
2145
2146
// Not optimal but we very rarely use this function.
2147
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2148
{
2149
    unsigned int unused = 0;
2150
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2151
}
2152
2153
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2154
{
2155
    if (c < 0x80) return 1;
2156
    if (c < 0x800) return 2;
2157
    if (c < 0x10000) return 3;
2158
    if (c <= 0x10FFFF) return 4;
2159
    return 3;
2160
}
2161
2162
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2163
{
2164
    char* buf_p = out_buf;
2165
    const char* buf_end = out_buf + out_buf_size;
2166
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2167
    {
2168
        unsigned int c = (unsigned int)(*in_text++);
2169
        if (c < 0x80)
2170
            *buf_p++ = (char)c;
2171
        else
2172
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2173
    }
2174
    *buf_p = 0;
2175
    return (int)(buf_p - out_buf);
2176
}
2177
2178
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2179
{
2180
    int bytes_count = 0;
2181
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2182
    {
2183
        unsigned int c = (unsigned int)(*in_text++);
2184
        if (c < 0x80)
2185
            bytes_count++;
2186
        else
2187
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2188
    }
2189
    return bytes_count;
2190
}
2191
2192
//-----------------------------------------------------------------------------
2193
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2194
// Note: The Convert functions are early design which are not consistent with other API.
2195
//-----------------------------------------------------------------------------
2196
2197
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2198
{
2199
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2200
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2201
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2202
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2203
    return IM_COL32(r, g, b, 0xFF);
2204
}
2205
2206
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2207
{
2208
    float s = 1.0f / 255.0f;
2209
    return ImVec4(
2210
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2211
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2212
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2213
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2214
}
2215
2216
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2217
{
2218
    ImU32 out;
2219
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2220
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2221
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2222
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2223
    return out;
2224
}
2225
2226
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2227
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2228
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2229
{
2230
    float K = 0.f;
2231
    if (g < b)
2232
    {
2233
        ImSwap(g, b);
2234
        K = -1.f;
2235
    }
2236
    if (r < g)
2237
    {
2238
        ImSwap(r, g);
2239
        K = -2.f / 6.f - K;
2240
    }
2241
2242
    const float chroma = r - (g < b ? g : b);
2243
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2244
    out_s = chroma / (r + 1e-20f);
2245
    out_v = r;
2246
}
2247
2248
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2249
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2250
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2251
{
2252
    if (s == 0.0f)
2253
    {
2254
        // gray
2255
        out_r = out_g = out_b = v;
2256
        return;
2257
    }
2258
2259
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2260
    int   i = (int)h;
2261
    float f = h - (float)i;
2262
    float p = v * (1.0f - s);
2263
    float q = v * (1.0f - s * f);
2264
    float t = v * (1.0f - s * (1.0f - f));
2265
2266
    switch (i)
2267
    {
2268
    case 0: out_r = v; out_g = t; out_b = p; break;
2269
    case 1: out_r = q; out_g = v; out_b = p; break;
2270
    case 2: out_r = p; out_g = v; out_b = t; break;
2271
    case 3: out_r = p; out_g = q; out_b = v; break;
2272
    case 4: out_r = t; out_g = p; out_b = v; break;
2273
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2274
    }
2275
}
2276
2277
//-----------------------------------------------------------------------------
2278
// [SECTION] ImGuiStorage
2279
// Helper: Key->value storage
2280
//-----------------------------------------------------------------------------
2281
2282
// std::lower_bound but without the bullshit
2283
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2284
{
2285
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2286
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2287
    size_t count = (size_t)(last - first);
2288
    while (count > 0)
2289
    {
2290
        size_t count2 = count >> 1;
2291
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2292
        if (mid->key < key)
2293
        {
2294
            first = ++mid;
2295
            count -= count2 + 1;
2296
        }
2297
        else
2298
        {
2299
            count = count2;
2300
        }
2301
    }
2302
    return first;
2303
}
2304
2305
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2306
void ImGuiStorage::BuildSortByKey()
2307
{
2308
    struct StaticFunc
2309
    {
2310
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2311
        {
2312
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2313
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2314
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2315
            return 0;
2316
        }
2317
    };
2318
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2319
}
2320
2321
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2322
{
2323
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2324
    if (it == Data.end() || it->key != key)
2325
        return default_val;
2326
    return it->val_i;
2327
}
2328
2329
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2330
{
2331
    return GetInt(key, default_val ? 1 : 0) != 0;
2332
}
2333
2334
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2335
{
2336
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2337
    if (it == Data.end() || it->key != key)
2338
        return default_val;
2339
    return it->val_f;
2340
}
2341
2342
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2343
{
2344
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2345
    if (it == Data.end() || it->key != key)
2346
        return NULL;
2347
    return it->val_p;
2348
}
2349
2350
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2351
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2352
{
2353
    ImGuiStoragePair* it = LowerBound(Data, key);
2354
    if (it == Data.end() || it->key != key)
2355
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2356
    return &it->val_i;
2357
}
2358
2359
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2360
{
2361
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2362
}
2363
2364
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2365
{
2366
    ImGuiStoragePair* it = LowerBound(Data, key);
2367
    if (it == Data.end() || it->key != key)
2368
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2369
    return &it->val_f;
2370
}
2371
2372
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2373
{
2374
    ImGuiStoragePair* it = LowerBound(Data, key);
2375
    if (it == Data.end() || it->key != key)
2376
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2377
    return &it->val_p;
2378
}
2379
2380
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2381
void ImGuiStorage::SetInt(ImGuiID key, int val)
2382
{
2383
    ImGuiStoragePair* it = LowerBound(Data, key);
2384
    if (it == Data.end() || it->key != key)
2385
    {
2386
        Data.insert(it, ImGuiStoragePair(key, val));
2387
        return;
2388
    }
2389
    it->val_i = val;
2390
}
2391
2392
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2393
{
2394
    SetInt(key, val ? 1 : 0);
2395
}
2396
2397
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2398
{
2399
    ImGuiStoragePair* it = LowerBound(Data, key);
2400
    if (it == Data.end() || it->key != key)
2401
    {
2402
        Data.insert(it, ImGuiStoragePair(key, val));
2403
        return;
2404
    }
2405
    it->val_f = val;
2406
}
2407
2408
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2409
{
2410
    ImGuiStoragePair* it = LowerBound(Data, key);
2411
    if (it == Data.end() || it->key != key)
2412
    {
2413
        Data.insert(it, ImGuiStoragePair(key, val));
2414
        return;
2415
    }
2416
    it->val_p = val;
2417
}
2418
2419
void ImGuiStorage::SetAllInt(int v)
2420
{
2421
    for (int i = 0; i < Data.Size; i++)
2422
        Data[i].val_i = v;
2423
}
2424
2425
//-----------------------------------------------------------------------------
2426
// [SECTION] ImGuiTextFilter
2427
//-----------------------------------------------------------------------------
2428
2429
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2430
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2431
{
2432
    InputBuf[0] = 0;
2433
    CountGrep = 0;
2434
    if (default_filter)
2435
    {
2436
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2437
        Build();
2438
    }
2439
}
2440
2441
bool ImGuiTextFilter::Draw(const char* label, float width)
2442
{
2443
    if (width != 0.0f)
2444
        ImGui::SetNextItemWidth(width);
2445
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2446
    if (value_changed)
2447
        Build();
2448
    return value_changed;
2449
}
2450
2451
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2452
{
2453
    out->resize(0);
2454
    const char* wb = b;
2455
    const char* we = wb;
2456
    while (we < e)
2457
    {
2458
        if (*we == separator)
2459
        {
2460
            out->push_back(ImGuiTextRange(wb, we));
2461
            wb = we + 1;
2462
        }
2463
        we++;
2464
    }
2465
    if (wb != we)
2466
        out->push_back(ImGuiTextRange(wb, we));
2467
}
2468
2469
void ImGuiTextFilter::Build()
2470
{
2471
    Filters.resize(0);
2472
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2473
    input_range.split(',', &Filters);
2474
2475
    CountGrep = 0;
2476
    for (int i = 0; i != Filters.Size; i++)
2477
    {
2478
        ImGuiTextRange& f = Filters[i];
2479
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2480
            f.b++;
2481
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2482
            f.e--;
2483
        if (f.empty())
2484
            continue;
2485
        if (Filters[i].b[0] != '-')
2486
            CountGrep += 1;
2487
    }
2488
}
2489
2490
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2491
{
2492
    if (Filters.empty())
2493
        return true;
2494
2495
    if (text == NULL)
2496
        text = "";
2497
2498
    for (int i = 0; i != Filters.Size; i++)
2499
    {
2500
        const ImGuiTextRange& f = Filters[i];
2501
        if (f.empty())
2502
            continue;
2503
        if (f.b[0] == '-')
2504
        {
2505
            // Subtract
2506
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2507
                return false;
2508
        }
2509
        else
2510
        {
2511
            // Grep
2512
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2513
                return true;
2514
        }
2515
    }
2516
2517
    // Implicit * grep
2518
    if (CountGrep == 0)
2519
        return true;
2520
2521
    return false;
2522
}
2523
2524
//-----------------------------------------------------------------------------
2525
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2526
//-----------------------------------------------------------------------------
2527
2528
// On some platform vsnprintf() takes va_list by reference and modifies it.
2529
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2530
#ifndef va_copy
2531
#if defined(__GNUC__) || defined(__clang__)
2532
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2533
#else
2534
#define va_copy(dest, src) (dest = src)
2535
#endif
2536
#endif
2537
2538
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2539
2540
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2541
{
2542
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2543
2544
    // Add zero-terminator the first time
2545
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2546
    const int needed_sz = write_off + len;
2547
    if (write_off + len >= Buf.Capacity)
2548
    {
2549
        int new_capacity = Buf.Capacity * 2;
2550
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2551
    }
2552
2553
    Buf.resize(needed_sz);
2554
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2555
    Buf[write_off - 1 + len] = 0;
2556
}
2557
2558
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2559
{
2560
    va_list args;
2561
    va_start(args, fmt);
2562
    appendfv(fmt, args);
2563
    va_end(args);
2564
}
2565
2566
// Helper: Text buffer for logging/accumulating text
2567
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2568
{
2569
    va_list args_copy;
2570
    va_copy(args_copy, args);
2571
2572
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2573
    if (len <= 0)
2574
    {
2575
        va_end(args_copy);
2576
        return;
2577
    }
2578
2579
    // Add zero-terminator the first time
2580
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2581
    const int needed_sz = write_off + len;
2582
    if (write_off + len >= Buf.Capacity)
2583
    {
2584
        int new_capacity = Buf.Capacity * 2;
2585
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2586
    }
2587
2588
    Buf.resize(needed_sz);
2589
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2590
    va_end(args_copy);
2591
}
2592
2593
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2594
{
2595
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2596
    if (old_size == new_size)
2597
        return;
2598
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2599
        LineOffsets.push_back(EndOffset);
2600
    const char* base_end = base + new_size;
2601
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2602
        if (++p < base_end) // Don't push a trailing offset on last \n
2603
            LineOffsets.push_back((int)(intptr_t)(p - base));
2604
    EndOffset = ImMax(EndOffset, new_size);
2605
}
2606
2607
//-----------------------------------------------------------------------------
2608
// [SECTION] ImGuiListClipper
2609
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
2610
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
2611
//-----------------------------------------------------------------------------
2612
2613
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2614
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2615
static bool GetSkipItemForListClipping()
2616
{
2617
    ImGuiContext& g = *GImGui;
2618
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2619
}
2620
2621
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2622
// Legacy helper to calculate coarse clipping of large list of evenly sized items.
2623
// This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
2624
// Prefer using ImGuiListClipper which can returns non-contiguous ranges.
2625
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2626
{
2627
    ImGuiContext& g = *GImGui;
2628
    ImGuiWindow* window = g.CurrentWindow;
2629
    if (g.LogEnabled)
2630
    {
2631
        // If logging is active, do not perform any clipping
2632
        *out_items_display_start = 0;
2633
        *out_items_display_end = items_count;
2634
        return;
2635
    }
2636
    if (GetSkipItemForListClipping())
2637
    {
2638
        *out_items_display_start = *out_items_display_end = 0;
2639
        return;
2640
    }
2641
2642
    // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2643
    // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
2644
    ImRect rect = window->ClipRect;
2645
    if (g.NavMoveScoringItems)
2646
        rect.Add(g.NavScoringNoClipRect);
2647
    if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2648
        rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
2649
2650
    const ImVec2 pos = window->DC.CursorPos;
2651
    int start = (int)((rect.Min.y - pos.y) / items_height);
2652
    int end = (int)((rect.Max.y - pos.y) / items_height);
2653
2654
    // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2655
    // FIXME: Verify this works with tabbing
2656
    const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2657
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
2658
        start--;
2659
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
2660
        end++;
2661
2662
    start = ImClamp(start, 0, items_count);
2663
    end = ImClamp(end + 1, start, items_count);
2664
    *out_items_display_start = start;
2665
    *out_items_display_end = end;
2666
}
2667
#endif
2668
2669
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2670
{
2671
    if (ranges.Size - offset <= 1)
2672
        return;
2673
2674
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2675
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2676
        for (int i = offset; i < sort_end + offset; ++i)
2677
            if (ranges[i].Min > ranges[i + 1].Min)
2678
                ImSwap(ranges[i], ranges[i + 1]);
2679
2680
    // Now fuse ranges together as much as possible.
2681
    for (int i = 1 + offset; i < ranges.Size; i++)
2682
    {
2683
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2684
        if (ranges[i - 1].Max < ranges[i].Min)
2685
            continue;
2686
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2687
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2688
        ranges.erase(ranges.Data + i);
2689
        i--;
2690
    }
2691
}
2692
2693
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2694
{
2695
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2696
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2697
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2698
    ImGuiContext& g = *GImGui;
2699
    ImGuiWindow* window = g.CurrentWindow;
2700
    float off_y = pos_y - window->DC.CursorPos.y;
2701
    window->DC.CursorPos.y = pos_y;
2702
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2703
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2704
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2705
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2706
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2707
    if (ImGuiTable* table = g.CurrentTable)
2708
    {
2709
        if (table->IsInsideRow)
2710
            ImGui::TableEndRow(table);
2711
        table->RowPosY2 = window->DC.CursorPos.y;
2712
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2713
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2714
        table->RowBgColorCounter += row_increase;
2715
    }
2716
}
2717
2718
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2719
{
2720
    // StartPosY starts from ItemsFrozen hence the subtraction
2721
    // Perform the add and multiply with double to allow seeking through larger ranges
2722
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2723
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2724
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2725
}
2726
2727
ImGuiListClipper::ImGuiListClipper()
2728
{
2729
    memset(this, 0, sizeof(*this));
2730
    ItemsCount = -1;
2731
}
2732
2733
ImGuiListClipper::~ImGuiListClipper()
2734
{
2735
    End();
2736
}
2737
2738
void ImGuiListClipper::Begin(int items_count, float items_height)
2739
{
2740
    ImGuiContext& g = *GImGui;
2741
    ImGuiWindow* window = g.CurrentWindow;
2742
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2743
2744
    if (ImGuiTable* table = g.CurrentTable)
2745
        if (table->IsInsideRow)
2746
            ImGui::TableEndRow(table);
2747
2748
    StartPosY = window->DC.CursorPos.y;
2749
    ItemsHeight = items_height;
2750
    ItemsCount = items_count;
2751
    DisplayStart = -1;
2752
    DisplayEnd = 0;
2753
2754
    // Acquire temporary buffer
2755
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2756
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2757
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2758
    data->Reset(this);
2759
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2760
    TempData = data;
2761
}
2762
2763
void ImGuiListClipper::End()
2764
{
2765
    ImGuiContext& g = *GImGui;
2766
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2767
    {
2768
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2769
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2770
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2771
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2772
2773
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2774
        IM_ASSERT(data->ListClipper == this);
2775
        data->StepNo = data->Ranges.Size;
2776
        if (--g.ClipperTempDataStacked > 0)
2777
        {
2778
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2779
            data->ListClipper->TempData = data;
2780
        }
2781
        TempData = NULL;
2782
    }
2783
    ItemsCount = -1;
2784
}
2785
2786
void ImGuiListClipper::ForceDisplayRangeByIndices(int item_min, int item_max)
2787
{
2788
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2789
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2790
    IM_ASSERT(item_min <= item_max);
2791
    if (item_min < item_max)
2792
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_min, item_max));
2793
}
2794
2795
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2796
{
2797
    ImGuiContext& g = *GImGui;
2798
    ImGuiWindow* window = g.CurrentWindow;
2799
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2800
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2801
2802
    ImGuiTable* table = g.CurrentTable;
2803
    if (table && table->IsInsideRow)
2804
        ImGui::TableEndRow(table);
2805
2806
    // No items
2807
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2808
        return false;
2809
2810
    // While we are in frozen row state, keep displaying items one by one, unclipped
2811
    // FIXME: Could be stored as a table-agnostic state.
2812
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2813
    {
2814
        clipper->DisplayStart = data->ItemsFrozen;
2815
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2816
        if (clipper->DisplayStart < clipper->DisplayEnd)
2817
            data->ItemsFrozen++;
2818
        return true;
2819
    }
2820
2821
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2822
    bool calc_clipping = false;
2823
    if (data->StepNo == 0)
2824
    {
2825
        clipper->StartPosY = window->DC.CursorPos.y;
2826
        if (clipper->ItemsHeight <= 0.0f)
2827
        {
2828
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2829
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2830
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2831
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2832
            data->StepNo = 1;
2833
            return true;
2834
        }
2835
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2836
    }
2837
2838
    // Step 1: Let the clipper infer height from first range
2839
    if (clipper->ItemsHeight <= 0.0f)
2840
    {
2841
        IM_ASSERT(data->StepNo == 1);
2842
        if (table)
2843
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2844
2845
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2846
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2847
        if (affected_by_floating_point_precision)
2848
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2849
2850
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2851
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
2852
    }
2853
2854
    // Step 0 or 1: Calculate the actual ranges of visible elements.
2855
    const int already_submitted = clipper->DisplayEnd;
2856
    if (calc_clipping)
2857
    {
2858
        if (g.LogEnabled)
2859
        {
2860
            // If logging is active, do not perform any clipping
2861
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
2862
        }
2863
        else
2864
        {
2865
            // Add range selected to be included for navigation
2866
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2867
            if (is_nav_request)
2868
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
2869
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && g.NavTabbingDir == -1)
2870
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
2871
2872
            // Add focused/active item
2873
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
2874
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
2875
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
2876
2877
            // Add visible range
2878
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
2879
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
2880
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
2881
        }
2882
2883
        // Convert position ranges to item index ranges
2884
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
2885
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
2886
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
2887
        for (int i = 0; i < data->Ranges.Size; i++)
2888
            if (data->Ranges[i].PosToIndexConvert)
2889
            {
2890
                int m1 = (int)(((double)data->Ranges[i].Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
2891
                int m2 = (int)((((double)data->Ranges[i].Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
2892
                data->Ranges[i].Min = ImClamp(already_submitted + m1 + data->Ranges[i].PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
2893
                data->Ranges[i].Max = ImClamp(already_submitted + m2 + data->Ranges[i].PosToIndexOffsetMax, data->Ranges[i].Min + 1, clipper->ItemsCount);
2894
                data->Ranges[i].PosToIndexConvert = false;
2895
            }
2896
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
2897
    }
2898
2899
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
2900
    if (data->StepNo < data->Ranges.Size)
2901
    {
2902
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
2903
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
2904
        if (clipper->DisplayStart > already_submitted) //-V1051
2905
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
2906
        data->StepNo++;
2907
        return true;
2908
    }
2909
2910
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
2911
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
2912
    if (clipper->ItemsCount < INT_MAX)
2913
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
2914
2915
    return false;
2916
}
2917
2918
bool ImGuiListClipper::Step()
2919
{
2920
    ImGuiContext& g = *GImGui;
2921
    bool need_items_height = (ItemsHeight <= 0.0f);
2922
    bool ret = ImGuiListClipper_StepInternal(this);
2923
    if (ret && (DisplayStart == DisplayEnd))
2924
        ret = false;
2925
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
2926
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
2927
    if (need_items_height && ItemsHeight > 0.0f)
2928
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
2929
    if (ret)
2930
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
2931
    else
2932
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
2933
    if (!ret)
2934
        End();
2935
    return ret;
2936
}
2937
2938
//-----------------------------------------------------------------------------
2939
// [SECTION] STYLING
2940
//-----------------------------------------------------------------------------
2941
2942
ImGuiStyle& ImGui::GetStyle()
2943
{
2944
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
2945
    return GImGui->Style;
2946
}
2947
2948
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
2949
{
2950
    ImGuiStyle& style = GImGui->Style;
2951
    ImVec4 c = style.Colors[idx];
2952
    c.w *= style.Alpha * alpha_mul;
2953
    return ColorConvertFloat4ToU32(c);
2954
}
2955
2956
ImU32 ImGui::GetColorU32(const ImVec4& col)
2957
{
2958
    ImGuiStyle& style = GImGui->Style;
2959
    ImVec4 c = col;
2960
    c.w *= style.Alpha;
2961
    return ColorConvertFloat4ToU32(c);
2962
}
2963
2964
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
2965
{
2966
    ImGuiStyle& style = GImGui->Style;
2967
    return style.Colors[idx];
2968
}
2969
2970
ImU32 ImGui::GetColorU32(ImU32 col)
2971
{
2972
    ImGuiStyle& style = GImGui->Style;
2973
    if (style.Alpha >= 1.0f)
2974
        return col;
2975
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
2976
    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
2977
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
2978
}
2979
2980
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
2981
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
2982
{
2983
    ImGuiContext& g = *GImGui;
2984
    ImGuiColorMod backup;
2985
    backup.Col = idx;
2986
    backup.BackupValue = g.Style.Colors[idx];
2987
    g.ColorStack.push_back(backup);
2988
    g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
2989
}
2990
2991
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
2992
{
2993
    ImGuiContext& g = *GImGui;
2994
    ImGuiColorMod backup;
2995
    backup.Col = idx;
2996
    backup.BackupValue = g.Style.Colors[idx];
2997
    g.ColorStack.push_back(backup);
2998
    g.Style.Colors[idx] = col;
2999
}
3000
3001
void ImGui::PopStyleColor(int count)
3002
{
3003
    ImGuiContext& g = *GImGui;
3004
    if (g.ColorStack.Size < count)
3005
    {
3006
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3007
        count = g.ColorStack.Size;
3008
    }
3009
    while (count > 0)
3010
    {
3011
        ImGuiColorMod& backup = g.ColorStack.back();
3012
        g.Style.Colors[backup.Col] = backup.BackupValue;
3013
        g.ColorStack.pop_back();
3014
        count--;
3015
    }
3016
}
3017
3018
struct ImGuiStyleVarInfo
3019
{
3020
    ImGuiDataType   Type;
3021
    ImU32           Count;
3022
    ImU32           Offset;
3023
    void*           GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
3024
};
3025
3026
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3027
{
3028
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3029
};
3030
3031
static const ImGuiStyleVarInfo GStyleVarInfo[] =
3032
{
3033
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },               // ImGuiStyleVar_Alpha
3034
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) },       // ImGuiStyleVar_DisabledAlpha
3035
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },       // ImGuiStyleVar_WindowPadding
3036
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },      // ImGuiStyleVar_WindowRounding
3037
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) },    // ImGuiStyleVar_WindowBorderSize
3038
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },       // ImGuiStyleVar_WindowMinSize
3039
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) },    // ImGuiStyleVar_WindowTitleAlign
3040
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) },       // ImGuiStyleVar_ChildRounding
3041
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) },     // ImGuiStyleVar_ChildBorderSize
3042
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) },       // ImGuiStyleVar_PopupRounding
3043
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) },     // ImGuiStyleVar_PopupBorderSize
3044
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },        // ImGuiStyleVar_FramePadding
3045
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },       // ImGuiStyleVar_FrameRounding
3046
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) },     // ImGuiStyleVar_FrameBorderSize
3047
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },         // ImGuiStyleVar_ItemSpacing
3048
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },    // ImGuiStyleVar_ItemInnerSpacing
3049
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },       // ImGuiStyleVar_IndentSpacing
3050
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) },         // ImGuiStyleVar_CellPadding
3051
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) },       // ImGuiStyleVar_ScrollbarSize
3052
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) },   // ImGuiStyleVar_ScrollbarRounding
3053
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },         // ImGuiStyleVar_GrabMinSize
3054
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) },        // ImGuiStyleVar_GrabRounding
3055
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) },         // ImGuiStyleVar_TabRounding
3056
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },     // ImGuiStyleVar_ButtonTextAlign
3057
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3058
};
3059
3060
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
3061
{
3062
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3063
    IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3064
    return &GStyleVarInfo[idx];
3065
}
3066
3067
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3068
{
3069
    const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3070
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3071
    {
3072
        ImGuiContext& g = *GImGui;
3073
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3074
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3075
        *pvar = val;
3076
        return;
3077
    }
3078
    IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
3079
}
3080
3081
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3082
{
3083
    const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3084
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3085
    {
3086
        ImGuiContext& g = *GImGui;
3087
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3088
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3089
        *pvar = val;
3090
        return;
3091
    }
3092
    IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
3093
}
3094
3095
void ImGui::PopStyleVar(int count)
3096
{
3097
    ImGuiContext& g = *GImGui;
3098
    if (g.StyleVarStack.Size < count)
3099
    {
3100
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3101
        count = g.StyleVarStack.Size;
3102
    }
3103
    while (count > 0)
3104
    {
3105
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3106
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3107
        const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3108
        void* data = info->GetVarPtr(&g.Style);
3109
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3110
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3111
        g.StyleVarStack.pop_back();
3112
        count--;
3113
    }
3114
}
3115
3116
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3117
{
3118
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3119
    switch (idx)
3120
    {
3121
    case ImGuiCol_Text: return "Text";
3122
    case ImGuiCol_TextDisabled: return "TextDisabled";
3123
    case ImGuiCol_WindowBg: return "WindowBg";
3124
    case ImGuiCol_ChildBg: return "ChildBg";
3125
    case ImGuiCol_PopupBg: return "PopupBg";
3126
    case ImGuiCol_Border: return "Border";
3127
    case ImGuiCol_BorderShadow: return "BorderShadow";
3128
    case ImGuiCol_FrameBg: return "FrameBg";
3129
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3130
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3131
    case ImGuiCol_TitleBg: return "TitleBg";
3132
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3133
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3134
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3135
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3136
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3137
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3138
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3139
    case ImGuiCol_CheckMark: return "CheckMark";
3140
    case ImGuiCol_SliderGrab: return "SliderGrab";
3141
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3142
    case ImGuiCol_Button: return "Button";
3143
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3144
    case ImGuiCol_ButtonActive: return "ButtonActive";
3145
    case ImGuiCol_Header: return "Header";
3146
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3147
    case ImGuiCol_HeaderActive: return "HeaderActive";
3148
    case ImGuiCol_Separator: return "Separator";
3149
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3150
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3151
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3152
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3153
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3154
    case ImGuiCol_Tab: return "Tab";
3155
    case ImGuiCol_TabHovered: return "TabHovered";
3156
    case ImGuiCol_TabActive: return "TabActive";
3157
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3158
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3159
    case ImGuiCol_DockingPreview: return "DockingPreview";
3160
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3161
    case ImGuiCol_PlotLines: return "PlotLines";
3162
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3163
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3164
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3165
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3166
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3167
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3168
    case ImGuiCol_TableRowBg: return "TableRowBg";
3169
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3170
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3171
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3172
    case ImGuiCol_NavHighlight: return "NavHighlight";
3173
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3174
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3175
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3176
    }
3177
    IM_ASSERT(0);
3178
    return "Unknown";
3179
}
3180
3181
3182
//-----------------------------------------------------------------------------
3183
// [SECTION] RENDER HELPERS
3184
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3185
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3186
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3187
//-----------------------------------------------------------------------------
3188
3189
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3190
{
3191
    const char* text_display_end = text;
3192
    if (!text_end)
3193
        text_end = (const char*)-1;
3194
3195
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3196
        text_display_end++;
3197
    return text_display_end;
3198
}
3199
3200
// Internal ImGui functions to render text
3201
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3202
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3203
{
3204
    ImGuiContext& g = *GImGui;
3205
    ImGuiWindow* window = g.CurrentWindow;
3206
3207
    // Hide anything after a '##' string
3208
    const char* text_display_end;
3209
    if (hide_text_after_hash)
3210
    {
3211
        text_display_end = FindRenderedTextEnd(text, text_end);
3212
    }
3213
    else
3214
    {
3215
        if (!text_end)
3216
            text_end = text + strlen(text); // FIXME-OPT
3217
        text_display_end = text_end;
3218
    }
3219
3220
    if (text != text_display_end)
3221
    {
3222
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3223
        if (g.LogEnabled)
3224
            LogRenderedText(&pos, text, text_display_end);
3225
    }
3226
}
3227
3228
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3229
{
3230
    ImGuiContext& g = *GImGui;
3231
    ImGuiWindow* window = g.CurrentWindow;
3232
3233
    if (!text_end)
3234
        text_end = text + strlen(text); // FIXME-OPT
3235
3236
    if (text != text_end)
3237
    {
3238
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3239
        if (g.LogEnabled)
3240
            LogRenderedText(&pos, text, text_end);
3241
    }
3242
}
3243
3244
// Default clip_rect uses (pos_min,pos_max)
3245
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3246
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3247
{
3248
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3249
    ImVec2 pos = pos_min;
3250
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3251
3252
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3253
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3254
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3255
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3256
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3257
3258
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3259
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3260
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3261
3262
    // Render
3263
    if (need_clipping)
3264
    {
3265
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3266
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3267
    }
3268
    else
3269
    {
3270
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3271
    }
3272
}
3273
3274
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3275
{
3276
    // Hide anything after a '##' string
3277
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3278
    const int text_len = (int)(text_display_end - text);
3279
    if (text_len == 0)
3280
        return;
3281
3282
    ImGuiContext& g = *GImGui;
3283
    ImGuiWindow* window = g.CurrentWindow;
3284
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3285
    if (g.LogEnabled)
3286
        LogRenderedText(&pos_min, text, text_display_end);
3287
}
3288
3289
3290
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3291
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3292
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3293
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3294
{
3295
    ImGuiContext& g = *GImGui;
3296
    if (text_end_full == NULL)
3297
        text_end_full = FindRenderedTextEnd(text);
3298
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3299
3300
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3301
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3302
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3303
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3304
    if (text_size.x > pos_max.x - pos_min.x)
3305
    {
3306
        // Hello wo...
3307
        // |       |   |
3308
        // min   max   ellipsis_max
3309
        //          <-> this is generally some padding value
3310
3311
        const ImFont* font = draw_list->_Data->Font;
3312
        const float font_size = draw_list->_Data->FontSize;
3313
        const char* text_end_ellipsis = NULL;
3314
3315
        ImWchar ellipsis_char = font->EllipsisChar;
3316
        int ellipsis_char_count = 1;
3317
        if (ellipsis_char == (ImWchar)-1)
3318
        {
3319
            ellipsis_char = font->DotChar;
3320
            ellipsis_char_count = 3;
3321
        }
3322
        const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char);
3323
3324
        float ellipsis_glyph_width = glyph->X1;                 // Width of the glyph with no padding on either side
3325
        float ellipsis_total_width = ellipsis_glyph_width;      // Full width of entire ellipsis
3326
3327
        if (ellipsis_char_count > 1)
3328
        {
3329
            // Full ellipsis size without free spacing after it.
3330
            const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize);
3331
            ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots;
3332
            ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots;
3333
        }
3334
3335
        // We can now claim the space between pos_max.x and ellipsis_max.x
3336
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f);
3337
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3338
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3339
        {
3340
            // Always display at least 1 character if there's no room for character + ellipsis
3341
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3342
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3343
        }
3344
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3345
        {
3346
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3347
            text_end_ellipsis--;
3348
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3349
        }
3350
3351
        // Render text, render ellipsis
3352
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3353
        float ellipsis_x = pos_min.x + text_size_clipped_x;
3354
        if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x)
3355
            for (int i = 0; i < ellipsis_char_count; i++)
3356
            {
3357
                font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char);
3358
                ellipsis_x += ellipsis_glyph_width;
3359
            }
3360
    }
3361
    else
3362
    {
3363
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3364
    }
3365
3366
    if (g.LogEnabled)
3367
        LogRenderedText(&pos_min, text, text_end_full);
3368
}
3369
3370
// Render a rectangle shaped with optional rounding and borders
3371
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3372
{
3373
    ImGuiContext& g = *GImGui;
3374
    ImGuiWindow* window = g.CurrentWindow;
3375
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3376
    const float border_size = g.Style.FrameBorderSize;
3377
    if (border && border_size > 0.0f)
3378
    {
3379
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3380
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3381
    }
3382
}
3383
3384
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3385
{
3386
    ImGuiContext& g = *GImGui;
3387
    ImGuiWindow* window = g.CurrentWindow;
3388
    const float border_size = g.Style.FrameBorderSize;
3389
    if (border_size > 0.0f)
3390
    {
3391
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3392
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3393
    }
3394
}
3395
3396
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3397
{
3398
    ImGuiContext& g = *GImGui;
3399
    if (id != g.NavId)
3400
        return;
3401
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3402
        return;
3403
    ImGuiWindow* window = g.CurrentWindow;
3404
    if (window->DC.NavHideHighlightOneFrame)
3405
        return;
3406
3407
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3408
    ImRect display_rect = bb;
3409
    display_rect.ClipWith(window->ClipRect);
3410
    if (flags & ImGuiNavHighlightFlags_TypeDefault)
3411
    {
3412
        const float THICKNESS = 2.0f;
3413
        const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3414
        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
3415
        bool fully_visible = window->ClipRect.Contains(display_rect);
3416
        if (!fully_visible)
3417
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3418
        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
3419
        if (!fully_visible)
3420
            window->DrawList->PopClipRect();
3421
    }
3422
    if (flags & ImGuiNavHighlightFlags_TypeThin)
3423
    {
3424
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
3425
    }
3426
}
3427
3428
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3429
{
3430
    ImGuiContext& g = *GImGui;
3431
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3432
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3433
    for (int n = 0; n < g.Viewports.Size; n++)
3434
    {
3435
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3436
        ImVec2 offset, size, uv[4];
3437
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3438
            continue;
3439
        ImGuiViewportP* viewport = g.Viewports[n];
3440
        const ImVec2 pos = base_pos - offset;
3441
        const float scale = base_scale * viewport->DpiScale;
3442
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3443
            continue;
3444
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3445
        ImTextureID tex_id = font_atlas->TexID;
3446
        draw_list->PushTextureID(tex_id);
3447
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3448
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3449
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3450
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3451
        draw_list->PopTextureID();
3452
    }
3453
}
3454
3455
3456
//-----------------------------------------------------------------------------
3457
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3458
//-----------------------------------------------------------------------------
3459
3460
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3461
ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL)
3462
{
3463
    memset(this, 0, sizeof(*this));
3464
    Name = ImStrdup(name);
3465
    NameBufLen = (int)strlen(name) + 1;
3466
    ID = ImHashStr(name);
3467
    IDStack.push_back(ID);
3468
    ViewportAllowPlatformMonitorExtend = -1;
3469
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3470
    MoveId = GetID("#MOVE");
3471
    TabId = GetID("#TAB");
3472
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3473
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3474
    AutoFitFramesX = AutoFitFramesY = -1;
3475
    AutoPosLastDirection = ImGuiDir_None;
3476
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
3477
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3478
    LastFrameActive = -1;
3479
    LastFrameJustFocused = -1;
3480
    LastTimeActive = -1.0f;
3481
    FontWindowScale = FontDpiScale = 1.0f;
3482
    SettingsOffset = -1;
3483
    DockOrder = -1;
3484
    DrawList = &DrawListInst;
3485
    DrawList->_Data = &context->DrawListSharedData;
3486
    DrawList->_OwnerName = Name;
3487
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3488
}
3489
3490
ImGuiWindow::~ImGuiWindow()
3491
{
3492
    IM_ASSERT(DrawList == &DrawListInst);
3493
    IM_DELETE(Name);
3494
    ColumnsStorage.clear_destruct();
3495
}
3496
3497
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3498
{
3499
    ImGuiID seed = IDStack.back();
3500
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3501
    ImGuiContext& g = *GImGui;
3502
    if (g.DebugHookIdInfo == id)
3503
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3504
    return id;
3505
}
3506
3507
ImGuiID ImGuiWindow::GetID(const void* ptr)
3508
{
3509
    ImGuiID seed = IDStack.back();
3510
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3511
    ImGuiContext& g = *GImGui;
3512
    if (g.DebugHookIdInfo == id)
3513
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3514
    return id;
3515
}
3516
3517
ImGuiID ImGuiWindow::GetID(int n)
3518
{
3519
    ImGuiID seed = IDStack.back();
3520
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
3521
    ImGuiContext& g = *GImGui;
3522
    if (g.DebugHookIdInfo == id)
3523
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3524
    return id;
3525
}
3526
3527
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3528
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3529
{
3530
    ImGuiID seed = IDStack.back();
3531
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3532
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3533
    return id;
3534
}
3535
3536
static void SetCurrentWindow(ImGuiWindow* window)
3537
{
3538
    ImGuiContext& g = *GImGui;
3539
    g.CurrentWindow = window;
3540
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3541
    if (window)
3542
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3543
}
3544
3545
void ImGui::GcCompactTransientMiscBuffers()
3546
{
3547
    ImGuiContext& g = *GImGui;
3548
    g.ItemFlagsStack.clear();
3549
    g.GroupStack.clear();
3550
    TableGcCompactSettings();
3551
}
3552
3553
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3554
// Not freed:
3555
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3556
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3557
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3558
{
3559
    window->MemoryCompacted = true;
3560
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3561
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3562
    window->IDStack.clear();
3563
    window->DrawList->_ClearFreeMemory();
3564
    window->DC.ChildWindows.clear();
3565
    window->DC.ItemWidthStack.clear();
3566
    window->DC.TextWrapPosStack.clear();
3567
}
3568
3569
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3570
{
3571
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3572
    // The other buffers tends to amortize much faster.
3573
    window->MemoryCompacted = false;
3574
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3575
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3576
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3577
}
3578
3579
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3580
{
3581
    ImGuiContext& g = *GImGui;
3582
3583
    // While most behaved code would make an effort to not steal active id during window move/drag operations,
3584
    // we at least need to be resilient to it. Cancelling the move is rather aggressive and users of 'master' branch
3585
    // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3586
    if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3587
    {
3588
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3589
        g.MovingWindow = NULL;
3590
    }
3591
3592
    // Set active id
3593
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3594
    if (g.ActiveIdIsJustActivated)
3595
    {
3596
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3597
        g.ActiveIdTimer = 0.0f;
3598
        g.ActiveIdHasBeenPressedBefore = false;
3599
        g.ActiveIdHasBeenEditedBefore = false;
3600
        g.ActiveIdMouseButton = -1;
3601
        if (id != 0)
3602
        {
3603
            g.LastActiveId = id;
3604
            g.LastActiveIdTimer = 0.0f;
3605
        }
3606
    }
3607
    g.ActiveId = id;
3608
    g.ActiveIdAllowOverlap = false;
3609
    g.ActiveIdNoClearOnFocusLoss = false;
3610
    g.ActiveIdWindow = window;
3611
    g.ActiveIdHasBeenEditedThisFrame = false;
3612
    if (id)
3613
    {
3614
        g.ActiveIdIsAlive = id;
3615
        g.ActiveIdSource = (g.NavActivateId == id || g.NavActivateInputId == id || g.NavJustMovedToId == id) ? (ImGuiInputSource)ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
3616
    }
3617
3618
    // Clear declaration of inputs claimed by the widget
3619
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3620
    g.ActiveIdUsingNavDirMask = 0x00;
3621
    g.ActiveIdUsingAllKeyboardKeys = false;
3622
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
3623
    g.ActiveIdUsingNavInputMask = 0x00;
3624
#endif
3625
}
3626
3627
void ImGui::ClearActiveID()
3628
{
3629
    SetActiveID(0, NULL); // g.ActiveId = 0;
3630
}
3631
3632
void ImGui::SetHoveredID(ImGuiID id)
3633
{
3634
    ImGuiContext& g = *GImGui;
3635
    g.HoveredId = id;
3636
    g.HoveredIdAllowOverlap = false;
3637
    if (id != 0 && g.HoveredIdPreviousFrame != id)
3638
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
3639
}
3640
3641
ImGuiID ImGui::GetHoveredID()
3642
{
3643
    ImGuiContext& g = *GImGui;
3644
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
3645
}
3646
3647
// This is called by ItemAdd().
3648
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
3649
void ImGui::KeepAliveID(ImGuiID id)
3650
{
3651
    ImGuiContext& g = *GImGui;
3652
    if (g.ActiveId == id)
3653
        g.ActiveIdIsAlive = id;
3654
    if (g.ActiveIdPreviousFrame == id)
3655
        g.ActiveIdPreviousFrameIsAlive = true;
3656
}
3657
3658
void ImGui::MarkItemEdited(ImGuiID id)
3659
{
3660
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
3661
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
3662
    ImGuiContext& g = *GImGui;
3663
    IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
3664
    IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
3665
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
3666
    g.ActiveIdHasBeenEditedThisFrame = true;
3667
    g.ActiveIdHasBeenEditedBefore = true;
3668
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
3669
}
3670
3671
static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
3672
{
3673
    // An active popup disable hovering on other windows (apart from its own children)
3674
    // FIXME-OPT: This could be cached/stored within the window.
3675
    ImGuiContext& g = *GImGui;
3676
    if (g.NavWindow)
3677
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
3678
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
3679
            {
3680
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
3681
                // NB: The 'else' is important because Modal windows are also Popups.
3682
                bool want_inhibit = false;
3683
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
3684
                    want_inhibit = true;
3685
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
3686
                    want_inhibit = true;
3687
3688
                // Inhibit hover unless the window is within the stack of our modal/popup
3689
                if (want_inhibit)
3690
                    if (!ImGui::IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
3691
                        return false;
3692
            }
3693
3694
    // Filter by viewport
3695
    if (window->Viewport != g.MouseViewport)
3696
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
3697
            return false;
3698
3699
    return true;
3700
}
3701
3702
// This is roughly matching the behavior of internal-facing ItemHoverable()
3703
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
3704
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
3705
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
3706
{
3707
    ImGuiContext& g = *GImGui;
3708
    ImGuiWindow* window = g.CurrentWindow;
3709
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
3710
    {
3711
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
3712
            return false;
3713
        if (!IsItemFocused())
3714
            return false;
3715
    }
3716
    else
3717
    {
3718
        // Test for bounding box overlap, as updated as ItemAdd()
3719
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
3720
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
3721
            return false;
3722
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
3723
3724
        // Done with rectangle culling so we can perform heavier checks now
3725
        // Test if we are hovering the right window (our window could be behind another window)
3726
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
3727
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
3728
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
3729
        // the test that has been running for a long while.
3730
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
3731
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)
3732
                return false;
3733
3734
        // Test if another item is active (e.g. being dragged)
3735
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
3736
            if (g.ActiveId != 0 && g.ActiveId != g.LastItemData.ID && !g.ActiveIdAllowOverlap)
3737
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
3738
                    return false;
3739
3740
        // Test if interactions on this window are blocked by an active popup or modal.
3741
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
3742
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
3743
            return false;
3744
3745
        // Test if the item is disabled
3746
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
3747
            return false;
3748
3749
        // Special handling for calling after Begin() which represent the title bar or tab.
3750
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
3751
        // will never be overwritten so we need to detect the case.
3752
        if (g.LastItemData.ID == window->MoveId && window->WriteAccessed)
3753
            return false;
3754
    }
3755
3756
    // Handle hover delay
3757
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
3758
    float delay;
3759
    if (flags & ImGuiHoveredFlags_DelayNormal)
3760
        delay = g.IO.HoverDelayNormal;
3761
    else if (flags & ImGuiHoveredFlags_DelayShort)
3762
        delay = g.IO.HoverDelayShort;
3763
    else
3764
        delay = 0.0f;
3765
    if (delay > 0.0f)
3766
    {
3767
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
3768
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverDelayIdPreviousFrame != hover_delay_id))
3769
            g.HoverDelayTimer = 0.0f;
3770
        g.HoverDelayId = hover_delay_id;
3771
        return g.HoverDelayTimer >= delay;
3772
    }
3773
3774
    return true;
3775
}
3776
3777
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
3778
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
3779
{
3780
    ImGuiContext& g = *GImGui;
3781
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
3782
        return false;
3783
3784
    ImGuiWindow* window = g.CurrentWindow;
3785
    if (g.HoveredWindow != window)
3786
        return false;
3787
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
3788
        return false;
3789
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
3790
        return false;
3791
3792
    // Done with rectangle culling so we can perform heavier checks now.
3793
    ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
3794
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
3795
    {
3796
        g.HoveredIdDisabled = true;
3797
        return false;
3798
    }
3799
3800
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
3801
    // hover test in widgets code. We could also decide to split this function is two.
3802
    if (id != 0)
3803
        SetHoveredID(id);
3804
3805
    // When disabled we'll return false but still set HoveredId
3806
    if (item_flags & ImGuiItemFlags_Disabled)
3807
    {
3808
        // Release active id if turning disabled
3809
        if (g.ActiveId == id)
3810
            ClearActiveID();
3811
        g.HoveredIdDisabled = true;
3812
        return false;
3813
    }
3814
3815
    if (id != 0)
3816
    {
3817
        // [DEBUG] Item Picker tool!
3818
        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
3819
        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
3820
        // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
3821
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
3822
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
3823
        if (g.DebugItemPickerBreakId == id)
3824
            IM_DEBUG_BREAK();
3825
    }
3826
3827
    if (g.NavDisableMouseHover)
3828
        return false;
3829
3830
    return true;
3831
}
3832
3833
// FIXME: This is inlined/duplicated in ItemAdd()
3834
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
3835
{
3836
    ImGuiContext& g = *GImGui;
3837
    ImGuiWindow* window = g.CurrentWindow;
3838
    if (!bb.Overlaps(window->ClipRect))
3839
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
3840
            if (!g.LogEnabled)
3841
                return true;
3842
    return false;
3843
}
3844
3845
// This is also inlined in ItemAdd()
3846
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect!
3847
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
3848
{
3849
    ImGuiContext& g = *GImGui;
3850
    g.LastItemData.ID = item_id;
3851
    g.LastItemData.InFlags = in_flags;
3852
    g.LastItemData.StatusFlags = item_flags;
3853
    g.LastItemData.Rect = item_rect;
3854
}
3855
3856
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
3857
{
3858
    if (wrap_pos_x < 0.0f)
3859
        return 0.0f;
3860
3861
    ImGuiContext& g = *GImGui;
3862
    ImGuiWindow* window = g.CurrentWindow;
3863
    if (wrap_pos_x == 0.0f)
3864
    {
3865
        // We could decide to setup a default wrapping max point for auto-resizing windows,
3866
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
3867
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
3868
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
3869
        //else
3870
        wrap_pos_x = window->WorkRect.Max.x;
3871
    }
3872
    else if (wrap_pos_x > 0.0f)
3873
    {
3874
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
3875
    }
3876
3877
    return ImMax(wrap_pos_x - pos.x, 1.0f);
3878
}
3879
3880
// IM_ALLOC() == ImGui::MemAlloc()
3881
void* ImGui::MemAlloc(size_t size)
3882
{
3883
    if (ImGuiContext* ctx = GImGui)
3884
        ctx->IO.MetricsActiveAllocations++;
3885
    return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
3886
}
3887
3888
// IM_FREE() == ImGui::MemFree()
3889
void ImGui::MemFree(void* ptr)
3890
{
3891
    if (ptr)
3892
        if (ImGuiContext* ctx = GImGui)
3893
            ctx->IO.MetricsActiveAllocations--;
3894
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
3895
}
3896
3897
const char* ImGui::GetClipboardText()
3898
{
3899
    ImGuiContext& g = *GImGui;
3900
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
3901
}
3902
3903
void ImGui::SetClipboardText(const char* text)
3904
{
3905
    ImGuiContext& g = *GImGui;
3906
    if (g.IO.SetClipboardTextFn)
3907
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
3908
}
3909
3910
const char* ImGui::GetVersion()
3911
{
3912
    return IMGUI_VERSION;
3913
}
3914
3915
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3916
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3917
ImGuiContext* ImGui::GetCurrentContext()
3918
{
3919
    return GImGui;
3920
}
3921
3922
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3923
{
3924
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3925
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3926
#else
3927
    GImGui = ctx;
3928
#endif
3929
}
3930
3931
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3932
{
3933
    GImAllocatorAllocFunc = alloc_func;
3934
    GImAllocatorFreeFunc = free_func;
3935
    GImAllocatorUserData = user_data;
3936
}
3937
3938
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3939
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3940
{
3941
    *p_alloc_func = GImAllocatorAllocFunc;
3942
    *p_free_func = GImAllocatorFreeFunc;
3943
    *p_user_data = GImAllocatorUserData;
3944
}
3945
3946
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3947
{
3948
    ImGuiContext* prev_ctx = GetCurrentContext();
3949
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3950
    SetCurrentContext(ctx);
3951
    Initialize();
3952
    if (prev_ctx != NULL)
3953
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3954
    return ctx;
3955
}
3956
3957
void ImGui::DestroyContext(ImGuiContext* ctx)
3958
{
3959
    ImGuiContext* prev_ctx = GetCurrentContext();
3960
    if (ctx == NULL) //-V1051
3961
        ctx = prev_ctx;
3962
    SetCurrentContext(ctx);
3963
    Shutdown();
3964
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3965
    IM_DELETE(ctx);
3966
}
3967
3968
// No specific ordering/dependency support, will see as needed
3969
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3970
{
3971
    ImGuiContext& g = *ctx;
3972
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3973
    g.Hooks.push_back(*hook);
3974
    g.Hooks.back().HookId = ++g.HookIdNext;
3975
    return g.HookIdNext;
3976
}
3977
3978
// Deferred removal, avoiding issue with changing vector while iterating it
3979
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3980
{
3981
    ImGuiContext& g = *ctx;
3982
    IM_ASSERT(hook_id != 0);
3983
    for (int n = 0; n < g.Hooks.Size; n++)
3984
        if (g.Hooks[n].HookId == hook_id)
3985
            g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
3986
}
3987
3988
// Call context hooks (used by e.g. test engine)
3989
// We assume a small number of hooks so all stored in same array
3990
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3991
{
3992
    ImGuiContext& g = *ctx;
3993
    for (int n = 0; n < g.Hooks.Size; n++)
3994
        if (g.Hooks[n].Type == hook_type)
3995
            g.Hooks[n].Callback(&g, &g.Hooks[n]);
3996
}
3997
3998
ImGuiIO& ImGui::GetIO()
3999
{
4000
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4001
    return GImGui->IO;
4002
}
4003
4004
ImGuiPlatformIO& ImGui::GetPlatformIO()
4005
{
4006
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4007
    return GImGui->PlatformIO;
4008
}
4009
4010
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4011
ImDrawData* ImGui::GetDrawData()
4012
{
4013
    ImGuiContext& g = *GImGui;
4014
    ImGuiViewportP* viewport = g.Viewports[0];
4015
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4016
}
4017
4018
double ImGui::GetTime()
4019
{
4020
    return GImGui->Time;
4021
}
4022
4023
int ImGui::GetFrameCount()
4024
{
4025
    return GImGui->FrameCount;
4026
}
4027
4028
static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4029
{
4030
    // Create the draw list on demand, because they are not frequently used for all viewports
4031
    ImGuiContext& g = *GImGui;
4032
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
4033
    ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
4034
    if (draw_list == NULL)
4035
    {
4036
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4037
        draw_list->_OwnerName = drawlist_name;
4038
        viewport->DrawLists[drawlist_no] = draw_list;
4039
    }
4040
4041
    // Our ImDrawList system requires that there is always a command
4042
    if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
4043
    {
4044
        draw_list->_ResetForNewFrame();
4045
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4046
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4047
        viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
4048
    }
4049
    return draw_list;
4050
}
4051
4052
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4053
{
4054
    return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4055
}
4056
4057
ImDrawList* ImGui::GetBackgroundDrawList()
4058
{
4059
    ImGuiContext& g = *GImGui;
4060
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4061
}
4062
4063
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4064
{
4065
    return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4066
}
4067
4068
ImDrawList* ImGui::GetForegroundDrawList()
4069
{
4070
    ImGuiContext& g = *GImGui;
4071
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4072
}
4073
4074
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4075
{
4076
    return &GImGui->DrawListSharedData;
4077
}
4078
4079
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4080
{
4081
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4082
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4083
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4084
    ImGuiContext& g = *GImGui;
4085
    FocusWindow(window);
4086
    SetActiveID(window->MoveId, window);
4087
    g.NavDisableHighlight = true;
4088
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4089
    g.ActiveIdNoClearOnFocusLoss = true;
4090
    SetActiveIdUsingAllKeyboardKeys();
4091
4092
    bool can_move_window = true;
4093
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4094
        can_move_window = false;
4095
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4096
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4097
            can_move_window = false;
4098
    if (can_move_window)
4099
        g.MovingWindow = window;
4100
}
4101
4102
// We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4103
// - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node.
4104
// - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window.
4105
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock_floating_node)
4106
{
4107
    ImGuiContext& g = *GImGui;
4108
    bool can_undock_node = false;
4109
    if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0)
4110
    {
4111
        // Can undock if:
4112
        // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy)
4113
        // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows)
4114
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4115
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4116
            if (undock_floating_node || root_node->IsDockSpace())
4117
                can_undock_node = true;
4118
    }
4119
4120
    const bool clicked = IsMouseClicked(0);
4121
    const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f);
4122
    if (can_undock_node && dragging)
4123
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4124
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4125
        StartMouseMovingWindow(window);
4126
}
4127
4128
// Handle mouse moving window
4129
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4130
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4131
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4132
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4133
void ImGui::UpdateMouseMovingWindowNewFrame()
4134
{
4135
    ImGuiContext& g = *GImGui;
4136
    if (g.MovingWindow != NULL)
4137
    {
4138
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4139
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4140
        KeepAliveID(g.ActiveId);
4141
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4142
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4143
4144
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4145
        const bool window_disappared = ((!moving_window->WasActive && !moving_window->Active) || moving_window->Viewport == NULL);
4146
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4147
        {
4148
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4149
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4150
            {
4151
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4152
                if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4153
                {
4154
                    moving_window->Viewport->Pos = pos;
4155
                    moving_window->Viewport->UpdateWorkRect();
4156
                }
4157
            }
4158
            FocusWindow(g.MovingWindow);
4159
        }
4160
        else
4161
        {
4162
            if (!window_disappared)
4163
            {
4164
                // Try to merge the window back into the main viewport.
4165
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4166
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4167
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4168
4169
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4170
                if (!IsDragDropPayloadBeingAccepted())
4171
                    g.MouseViewport = moving_window->Viewport;
4172
4173
                // Clear the NoInput window flag set by the Viewport system
4174
                moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; // FIXME-VIEWPORT: Test engine managed to crash here because Viewport was NULL.
4175
            }
4176
4177
            g.MovingWindow = NULL;
4178
            ClearActiveID();
4179
        }
4180
    }
4181
    else
4182
    {
4183
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4184
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4185
        {
4186
            KeepAliveID(g.ActiveId);
4187
            if (!g.IO.MouseDown[0])
4188
                ClearActiveID();
4189
        }
4190
    }
4191
}
4192
4193
// Initiate moving window when clicking on empty space or title bar.
4194
// Handle left-click and right-click focus.
4195
void ImGui::UpdateMouseMovingWindowEndFrame()
4196
{
4197
    ImGuiContext& g = *GImGui;
4198
    if (g.ActiveId != 0 || g.HoveredId != 0)
4199
        return;
4200
4201
    // Unless we just made a window/popup appear
4202
    if (g.NavWindow && g.NavWindow->Appearing)
4203
        return;
4204
4205
    // Click on empty space to focus window and start moving
4206
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4207
    if (g.IO.MouseClicked[0])
4208
    {
4209
        // Handle the edge case of a popup being closed while clicking in its empty space.
4210
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4211
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4212
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4213
4214
        if (root_window != NULL && !is_closed_popup)
4215
        {
4216
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4217
4218
            // Cancel moving if clicked outside of title bar
4219
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4220
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4221
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4222
                        g.MovingWindow = NULL;
4223
4224
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4225
            if (g.HoveredIdDisabled)
4226
                g.MovingWindow = NULL;
4227
        }
4228
        else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
4229
        {
4230
            // Clicking on void disable focus
4231
            FocusWindow(NULL);
4232
        }
4233
    }
4234
4235
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4236
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4237
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4238
    if (g.IO.MouseClicked[1])
4239
    {
4240
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4241
        // This is where we can trim the popup stack.
4242
        ImGuiWindow* modal = GetTopMostPopupModal();
4243
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4244
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4245
    }
4246
}
4247
4248
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4249
// Need to keep in sync with SetWindowPos()
4250
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4251
{
4252
    window->Pos += delta;
4253
    window->ClipRect.Translate(delta);
4254
    window->OuterRectClipped.Translate(delta);
4255
    window->InnerRect.Translate(delta);
4256
    window->DC.CursorPos += delta;
4257
    window->DC.CursorStartPos += delta;
4258
    window->DC.CursorMaxPos += delta;
4259
    window->DC.IdealMaxPos += delta;
4260
}
4261
4262
static void ScaleWindow(ImGuiWindow* window, float scale)
4263
{
4264
    ImVec2 origin = window->Viewport->Pos;
4265
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4266
    window->Size = ImFloor(window->Size * scale);
4267
    window->SizeFull = ImFloor(window->SizeFull * scale);
4268
    window->ContentSize = ImFloor(window->ContentSize * scale);
4269
}
4270
4271
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4272
{
4273
    return (window->Active) && (!window->Hidden);
4274
}
4275
4276
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
4277
{
4278
    IM_ASSERT(ImGui::IsAliasKey(key));
4279
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
4280
    key_data->Down = v;
4281
    key_data->AnalogValue = analog_value;
4282
}
4283
4284
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
4285
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
4286
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
4287
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
4288
static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
4289
{
4290
    ImGuiContext& g = *GImGui;
4291
    rt->EntriesNext.resize(0);
4292
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
4293
    {
4294
        const int new_routing_start_idx = rt->EntriesNext.Size;
4295
        ImGuiKeyRoutingData* routing_entry;
4296
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
4297
        {
4298
            routing_entry = &rt->Entries[old_routing_idx];
4299
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
4300
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
4301
            routing_entry->RoutingNextScore = 255;
4302
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
4303
                continue;
4304
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
4305
4306
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
4307
            if (routing_entry->Mods == g.IO.KeyMods)
4308
            {
4309
                ImGuiKeyOwnerData* owner_data = ImGui::GetKeyOwnerData(key);
4310
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
4311
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
4312
            }
4313
        }
4314
4315
        // Rewrite linked-list
4316
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
4317
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
4318
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
4319
    }
4320
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
4321
}
4322
4323
// [Internal] Do not use directly (should read io.KeyMods instead)
4324
static ImGuiKeyChord GetMergedModsFromBools()
4325
{
4326
    ImGuiContext& g = *GImGui;
4327
    ImGuiKeyChord key_chord = 0;
4328
    if (g.IO.KeyCtrl)  { key_chord |= ImGuiMod_Ctrl; }
4329
    if (g.IO.KeyShift) { key_chord |= ImGuiMod_Shift; }
4330
    if (g.IO.KeyAlt)   { key_chord |= ImGuiMod_Alt; }
4331
    if (g.IO.KeySuper) { key_chord |= ImGuiMod_Super; }
4332
    return key_chord;
4333
}
4334
4335
static void ImGui::UpdateKeyboardInputs()
4336
{
4337
    ImGuiContext& g = *GImGui;
4338
    ImGuiIO& io = g.IO;
4339
4340
    // Import legacy keys or verify they are not used
4341
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4342
    if (io.BackendUsingLegacyKeyArrays == 0)
4343
    {
4344
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
4345
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
4346
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
4347
    }
4348
    else
4349
    {
4350
        if (g.FrameCount == 0)
4351
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
4352
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
4353
4354
        // Build reverse KeyMap (Named -> Legacy)
4355
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
4356
            if (io.KeyMap[n] != -1)
4357
            {
4358
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
4359
                io.KeyMap[io.KeyMap[n]] = n;
4360
            }
4361
4362
        // Import legacy keys into new ones
4363
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
4364
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
4365
            {
4366
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
4367
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
4368
                io.KeysData[key].Down = io.KeysDown[n];
4369
                if (key != n)
4370
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
4371
                io.BackendUsingLegacyKeyArrays = 1;
4372
            }
4373
        if (io.BackendUsingLegacyKeyArrays == 1)
4374
        {
4375
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
4376
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
4377
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
4378
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
4379
        }
4380
    }
4381
4382
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4383
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
4384
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
4385
    {
4386
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
4387
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
4388
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
4389
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
4390
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
4391
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
4392
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
4393
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
4394
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
4395
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
4396
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
4397
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
4398
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
4399
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
4400
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
4401
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
4402
        #undef NAV_MAP_KEY
4403
    }
4404
#endif
4405
4406
#endif
4407
4408
    // Synchronize io.KeyMods with individual modifiers io.KeyXXX bools, update aliases
4409
    io.KeyMods = GetMergedModsFromBools();
4410
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
4411
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
4412
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
4413
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
4414
4415
    // Clear gamepad data if disabled
4416
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
4417
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
4418
        {
4419
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
4420
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
4421
        }
4422
4423
    // Update keys
4424
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
4425
    {
4426
        ImGuiKeyData* key_data = &io.KeysData[i];
4427
        key_data->DownDurationPrev = key_data->DownDuration;
4428
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
4429
    }
4430
4431
    // Update keys/input owner (named keys only): one entry per key
4432
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
4433
    {
4434
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
4435
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
4436
        owner_data->OwnerCurr = owner_data->OwnerNext;
4437
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
4438
            owner_data->OwnerNext = ImGuiKeyOwner_None;
4439
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
4440
    }
4441
4442
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
4443
}
4444
4445
static void ImGui::UpdateMouseInputs()
4446
{
4447
    ImGuiContext& g = *GImGui;
4448
    ImGuiIO& io = g.IO;
4449
4450
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
4451
    if (IsMousePosValid(&io.MousePos))
4452
        io.MousePos = g.MouseLastValidPos = ImFloorSigned(io.MousePos);
4453
4454
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
4455
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
4456
        io.MouseDelta = io.MousePos - io.MousePosPrev;
4457
    else
4458
        io.MouseDelta = ImVec2(0.0f, 0.0f);
4459
4460
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
4461
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
4462
        g.NavDisableMouseHover = false;
4463
4464
    io.MousePosPrev = io.MousePos;
4465
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4466
    {
4467
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
4468
        io.MouseClickedCount[i] = 0; // Will be filled below
4469
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
4470
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
4471
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
4472
        if (io.MouseClicked[i])
4473
        {
4474
            bool is_repeated_click = false;
4475
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
4476
            {
4477
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
4478
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
4479
                    is_repeated_click = true;
4480
            }
4481
            if (is_repeated_click)
4482
                io.MouseClickedLastCount[i]++;
4483
            else
4484
                io.MouseClickedLastCount[i] = 1;
4485
            io.MouseClickedTime[i] = g.Time;
4486
            io.MouseClickedPos[i] = io.MousePos;
4487
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
4488
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
4489
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
4490
        }
4491
        else if (io.MouseDown[i])
4492
        {
4493
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
4494
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
4495
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
4496
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
4497
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
4498
        }
4499
4500
        // We provide io.MouseDoubleClicked[] as a legacy service
4501
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
4502
4503
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
4504
        if (io.MouseClicked[i])
4505
            g.NavDisableMouseHover = false;
4506
    }
4507
}
4508
4509
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
4510
{
4511
    ImGuiContext& g = *GImGui;
4512
    if (window)
4513
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
4514
    else
4515
        g.WheelingWindowReleaseTimer = 0.0f;
4516
    if (g.WheelingWindow == window)
4517
        return;
4518
    IMGUI_DEBUG_LOG_IO("LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
4519
    g.WheelingWindow = window;
4520
    g.WheelingWindowRefMousePos = g.IO.MousePos;
4521
}
4522
4523
void ImGui::UpdateMouseWheel()
4524
{
4525
    ImGuiContext& g = *GImGui;
4526
4527
    // Reset the locked window if we move the mouse or after the timer elapses
4528
    if (g.WheelingWindow != NULL)
4529
    {
4530
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
4531
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
4532
            g.WheelingWindowReleaseTimer = 0.0f;
4533
        if (g.WheelingWindowReleaseTimer <= 0.0f)
4534
            LockWheelingWindow(NULL, 0.0f);
4535
    }
4536
4537
    ImVec2 wheel;
4538
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
4539
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
4540
    if (wheel.x == 0.0f && wheel.y == 0.0f)
4541
        return;
4542
4543
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
4544
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
4545
    if (!mouse_window || mouse_window->Collapsed)
4546
        return;
4547
4548
    // Zoom / Scale window
4549
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
4550
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
4551
    {
4552
        LockWheelingWindow(mouse_window, wheel.y);
4553
        ImGuiWindow* window = mouse_window;
4554
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
4555
        const float scale = new_font_scale / window->FontWindowScale;
4556
        window->FontWindowScale = new_font_scale;
4557
        if (window == window->RootWindow)
4558
        {
4559
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
4560
            SetWindowPos(window, window->Pos + offset, 0);
4561
            window->Size = ImFloor(window->Size * scale);
4562
            window->SizeFull = ImFloor(window->SizeFull * scale);
4563
        }
4564
        return;
4565
    }
4566
    if (g.IO.KeyCtrl)
4567
        return;
4568
4569
    // Mouse wheel scrolling
4570
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
4571
    // (we avoid doing it on OSX as it the OS input layer handles this already)
4572
    const bool swap_axis = g.IO.KeyShift && !g.IO.ConfigMacOSXBehaviors;
4573
    if (swap_axis)
4574
    {
4575
        wheel.x = wheel.y;
4576
        wheel.y = 0.0f;
4577
    }
4578
4579
    // Vertical Mouse Wheel scrolling
4580
    // Bubble up into parent window if:
4581
    // - a child window doesn't allow any scrolling.
4582
    // - a child window doesn't need scrolling because it is already at the edge for the direction we are going in.
4583
    // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
4584
    if (wheel.y != 0.0f)
4585
    {
4586
        ImGuiWindow* window = mouse_window;
4587
        while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
4588
            window = window->ParentWindow;
4589
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
4590
        {
4591
            LockWheelingWindow(mouse_window, wheel.y);
4592
            float max_step = window->InnerRect.GetHeight() * 0.67f;
4593
            float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
4594
            SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
4595
        }
4596
    }
4597
4598
    // Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
4599
    if (wheel.x != 0.0f)
4600
    {
4601
        ImGuiWindow* window = mouse_window;
4602
        while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
4603
            window = window->ParentWindow;
4604
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
4605
        {
4606
            LockWheelingWindow(mouse_window, wheel.x);
4607
            float max_step = window->InnerRect.GetWidth() * 0.67f;
4608
            float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
4609
            SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
4610
        }
4611
    }
4612
}
4613
4614
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4615
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4616
{
4617
    ImGuiContext& g = *GImGui;
4618
    ImGuiIO& io = g.IO;
4619
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4620
4621
    // Find the window hovered by mouse:
4622
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4623
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4624
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4625
    bool clear_hovered_windows = false;
4626
    FindHoveredWindow();
4627
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4628
4629
    // Modal windows prevents mouse from hovering behind them.
4630
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4631
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4632
        clear_hovered_windows = true;
4633
4634
    // Disabled mouse?
4635
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4636
        clear_hovered_windows = true;
4637
4638
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4639
    // won't report hovering nor request capture even while dragging over our windows afterward.
4640
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4641
    const bool has_open_modal = (modal_window != NULL);
4642
    int mouse_earliest_down = -1;
4643
    bool mouse_any_down = false;
4644
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4645
    {
4646
        if (io.MouseClicked[i])
4647
        {
4648
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4649
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4650
        }
4651
        mouse_any_down |= io.MouseDown[i];
4652
        if (io.MouseDown[i])
4653
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4654
                mouse_earliest_down = i;
4655
    }
4656
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4657
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4658
4659
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4660
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4661
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4662
    if (!mouse_avail && !mouse_dragging_extern_payload)
4663
        clear_hovered_windows = true;
4664
4665
    if (clear_hovered_windows)
4666
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4667
4668
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4669
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4670
    if (g.WantCaptureMouseNextFrame != -1)
4671
    {
4672
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4673
    }
4674
    else
4675
    {
4676
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4677
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4678
    }
4679
4680
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4681
    if (g.WantCaptureKeyboardNextFrame != -1)
4682
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4683
    else
4684
        io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4685
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4686
        io.WantCaptureKeyboard = true;
4687
4688
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4689
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4690
}
4691
4692
void ImGui::NewFrame()
4693
{
4694
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4695
    ImGuiContext& g = *GImGui;
4696
4697
    // Remove pending delete hooks before frame start.
4698
    // This deferred removal avoid issues of removal while iterating the hook vector
4699
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4700
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4701
            g.Hooks.erase(&g.Hooks[n]);
4702
4703
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4704
4705
    // Check and assert for various common IO and Configuration mistakes
4706
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4707
    ErrorCheckNewFrameSanityChecks();
4708
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4709
4710
    // Load settings on first frame, save settings when modified (after a delay)
4711
    UpdateSettings();
4712
4713
    g.Time += g.IO.DeltaTime;
4714
    g.WithinFrameScope = true;
4715
    g.FrameCount += 1;
4716
    g.TooltipOverrideCount = 0;
4717
    g.WindowsActiveCount = 0;
4718
    g.MenusIdSubmittedThisFrame.resize(0);
4719
4720
    // Calculate frame-rate for the user, as a purely luxurious feature
4721
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4722
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4723
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4724
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4725
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4726
4727
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4728
    g.InputEventsTrail.resize(0);
4729
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4730
4731
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4732
    UpdateViewportsNewFrame();
4733
4734
    // Setup current font and draw list shared data
4735
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4736
    g.IO.Fonts->Locked = true;
4737
    SetCurrentFont(GetDefaultFont());
4738
    IM_ASSERT(g.Font->IsLoaded());
4739
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4740
    for (int n = 0; n < g.Viewports.Size; n++)
4741
        virtual_space.Add(g.Viewports[n]->GetMainRect());
4742
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4743
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4744
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4745
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4746
    if (g.Style.AntiAliasedLines)
4747
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4748
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4749
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4750
    if (g.Style.AntiAliasedFill)
4751
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4752
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4753
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4754
4755
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4756
    for (int n = 0; n < g.Viewports.Size; n++)
4757
    {
4758
        ImGuiViewportP* viewport = g.Viewports[n];
4759
        viewport->DrawData = NULL;
4760
        viewport->DrawDataP.Clear();
4761
    }
4762
4763
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4764
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4765
        KeepAliveID(g.DragDropPayload.SourceId);
4766
4767
    // Update HoveredId data
4768
    if (!g.HoveredIdPreviousFrame)
4769
        g.HoveredIdTimer = 0.0f;
4770
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4771
        g.HoveredIdNotActiveTimer = 0.0f;
4772
    if (g.HoveredId)
4773
        g.HoveredIdTimer += g.IO.DeltaTime;
4774
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4775
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4776
    g.HoveredIdPreviousFrame = g.HoveredId;
4777
    g.HoveredId = 0;
4778
    g.HoveredIdAllowOverlap = false;
4779
    g.HoveredIdDisabled = false;
4780
4781
    // Clear ActiveID if the item is not alive anymore.
4782
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4783
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4784
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4785
    {
4786
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4787
        ClearActiveID();
4788
    }
4789
4790
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4791
    if (g.ActiveId)
4792
        g.ActiveIdTimer += g.IO.DeltaTime;
4793
    g.LastActiveIdTimer += g.IO.DeltaTime;
4794
    g.ActiveIdPreviousFrame = g.ActiveId;
4795
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4796
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4797
    g.ActiveIdIsAlive = 0;
4798
    g.ActiveIdHasBeenEditedThisFrame = false;
4799
    g.ActiveIdPreviousFrameIsAlive = false;
4800
    g.ActiveIdIsJustActivated = false;
4801
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4802
        g.TempInputId = 0;
4803
    if (g.ActiveId == 0)
4804
    {
4805
        g.ActiveIdUsingNavDirMask = 0x00;
4806
        g.ActiveIdUsingAllKeyboardKeys = false;
4807
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4808
        g.ActiveIdUsingNavInputMask = 0x00;
4809
#endif
4810
    }
4811
4812
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4813
    if (g.ActiveId == 0)
4814
        g.ActiveIdUsingNavInputMask = 0;
4815
    else if (g.ActiveIdUsingNavInputMask != 0)
4816
    {
4817
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4818
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4819
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4820
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4821
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4822
            IM_ASSERT(0); // Other values unsupported
4823
    }
4824
#endif
4825
4826
    // Update hover delay for IsItemHovered() with delays and tooltips
4827
    g.HoverDelayIdPreviousFrame = g.HoverDelayId;
4828
    if (g.HoverDelayId != 0)
4829
    {
4830
        //if (g.IO.MouseDelta.x == 0.0f && g.IO.MouseDelta.y == 0.0f) // Need design/flags
4831
        g.HoverDelayTimer += g.IO.DeltaTime;
4832
        g.HoverDelayClearTimer = 0.0f;
4833
        g.HoverDelayId = 0;
4834
    }
4835
    else if (g.HoverDelayTimer > 0.0f)
4836
    {
4837
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4838
        g.HoverDelayClearTimer += g.IO.DeltaTime;
4839
        if (g.HoverDelayClearTimer >= ImMax(0.20f, g.IO.DeltaTime * 2.0f)) // ~6 frames at 30 Hz + allow for low framerate
4840
            g.HoverDelayTimer = g.HoverDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4841
    }
4842
4843
    // Drag and drop
4844
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4845
    g.DragDropAcceptIdCurr = 0;
4846
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4847
    g.DragDropWithinSource = false;
4848
    g.DragDropWithinTarget = false;
4849
    g.DragDropHoldJustPressedId = 0;
4850
4851
    // Close popups on focus lost (currently wip/opt-in)
4852
    //if (g.IO.AppFocusLost)
4853
    //    ClosePopupsExceptModals();
4854
4855
    // Update keyboard input state
4856
    UpdateKeyboardInputs();
4857
4858
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4859
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4860
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4861
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4862
4863
    // Update gamepad/keyboard navigation
4864
    NavUpdate();
4865
4866
    // Update mouse input state
4867
    UpdateMouseInputs();
4868
4869
    // Undocking
4870
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4871
    DockContextNewFrameUpdateUndocking(&g);
4872
4873
    // Find hovered window
4874
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4875
    UpdateHoveredWindowAndCaptureFlags();
4876
4877
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4878
    UpdateMouseMovingWindowNewFrame();
4879
4880
    // Background darkening/whitening
4881
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4882
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4883
    else
4884
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4885
4886
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4887
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4888
4889
    // Platform IME data: reset for the frame
4890
    g.PlatformImeDataPrev = g.PlatformImeData;
4891
    g.PlatformImeData.WantVisible = false;
4892
4893
    // Mouse wheel scrolling, scale
4894
    UpdateMouseWheel();
4895
4896
    // Mark all windows as not visible and compact unused memory.
4897
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4898
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4899
    for (int i = 0; i != g.Windows.Size; i++)
4900
    {
4901
        ImGuiWindow* window = g.Windows[i];
4902
        window->WasActive = window->Active;
4903
        window->Active = false;
4904
        window->WriteAccessed = false;
4905
        window->BeginCountPreviousFrame = window->BeginCount;
4906
        window->BeginCount = 0;
4907
4908
        // Garbage collect transient buffers of recently unused windows
4909
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4910
            GcCompactTransientWindowBuffers(window);
4911
    }
4912
4913
    // Garbage collect transient buffers of recently unused tables
4914
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4915
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4916
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4917
    for (int i = 0; i < g.TablesTempData.Size; i++)
4918
        if (g.TablesTempData[i].LastTimeActive >= 0.0f && g.TablesTempData[i].LastTimeActive < memory_compact_start_time)
4919
            TableGcCompactTransientBuffers(&g.TablesTempData[i]);
4920
    if (g.GcCompactAll)
4921
        GcCompactTransientMiscBuffers();
4922
    g.GcCompactAll = false;
4923
4924
    // Closing the focused window restore focus to the first active root window in descending z-order
4925
    if (g.NavWindow && !g.NavWindow->WasActive)
4926
        FocusTopMostWindowUnderOne(NULL, NULL);
4927
4928
    // No window should be open at the beginning of the frame.
4929
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4930
    g.CurrentWindowStack.resize(0);
4931
    g.BeginPopupStack.resize(0);
4932
    g.ItemFlagsStack.resize(0);
4933
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4934
    g.GroupStack.resize(0);
4935
4936
    // Docking
4937
    DockContextNewFrameUpdateDocking(&g);
4938
4939
    // [DEBUG] Update debug features
4940
    UpdateDebugToolItemPicker();
4941
    UpdateDebugToolStackQueries();
4942
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4943
        g.DebugLocateId = 0;
4944
4945
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
4946
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4947
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
4948
    g.WithinFrameScopeWithImplicitWindow = true;
4949
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
4950
    Begin("Debug##Default");
4951
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4952
4953
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
4954
}
4955
4956
void ImGui::Initialize()
4957
{
4958
    ImGuiContext& g = *GImGui;
4959
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
4960
4961
    // Add .ini handle for ImGuiWindow type
4962
    {
4963
        ImGuiSettingsHandler ini_handler;
4964
        ini_handler.TypeName = "Window";
4965
        ini_handler.TypeHash = ImHashStr("Window");
4966
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
4967
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
4968
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
4969
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
4970
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
4971
        AddSettingsHandler(&ini_handler);
4972
    }
4973
4974
    // Add .ini handle for ImGuiTable type
4975
    TableSettingsAddSettingsHandler();
4976
4977
    // Create default viewport
4978
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
4979
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
4980
    viewport->Idx = 0;
4981
    viewport->PlatformWindowCreated = true;
4982
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
4983
    g.Viewports.push_back(viewport);
4984
    g.TempBuffer.resize(1024 * 3 + 1, 0);
4985
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
4986
4987
#ifdef IMGUI_HAS_DOCK
4988
    // Initialize Docking
4989
    DockContextInitialize(&g);
4990
#endif
4991
4992
    g.Initialized = true;
4993
}
4994
4995
// This function is merely here to free heap allocations.
4996
void ImGui::Shutdown()
4997
{
4998
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
4999
    ImGuiContext& g = *GImGui;
5000
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
5001
    {
5002
        g.IO.Fonts->Locked = false;
5003
        IM_DELETE(g.IO.Fonts);
5004
    }
5005
    g.IO.Fonts = NULL;
5006
    g.DrawListSharedData.TempBuffer.clear();
5007
5008
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
5009
    if (!g.Initialized)
5010
        return;
5011
5012
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
5013
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
5014
        SaveIniSettingsToDisk(g.IO.IniFilename);
5015
5016
    // Destroy platform windows
5017
    DestroyPlatformWindows();
5018
5019
    // Shutdown extensions
5020
    DockContextShutdown(&g);
5021
5022
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
5023
5024
    // Clear everything else
5025
    g.Windows.clear_delete();
5026
    g.WindowsFocusOrder.clear();
5027
    g.WindowsTempSortBuffer.clear();
5028
    g.CurrentWindow = NULL;
5029
    g.CurrentWindowStack.clear();
5030
    g.WindowsById.Clear();
5031
    g.NavWindow = NULL;
5032
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
5033
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
5034
    g.MovingWindow = NULL;
5035
5036
    g.KeysRoutingTable.Clear();
5037
5038
    g.ColorStack.clear();
5039
    g.StyleVarStack.clear();
5040
    g.FontStack.clear();
5041
    g.OpenPopupStack.clear();
5042
    g.BeginPopupStack.clear();
5043
5044
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
5045
    g.Viewports.clear_delete();
5046
5047
    g.TabBars.Clear();
5048
    g.CurrentTabBarStack.clear();
5049
    g.ShrinkWidthBuffer.clear();
5050
5051
    g.ClipperTempData.clear_destruct();
5052
5053
    g.Tables.Clear();
5054
    g.TablesTempData.clear_destruct();
5055
    g.DrawChannelsTempMergeBuffer.clear();
5056
5057
    g.ClipboardHandlerData.clear();
5058
    g.MenusIdSubmittedThisFrame.clear();
5059
    g.InputTextState.ClearFreeMemory();
5060
5061
    g.SettingsWindows.clear();
5062
    g.SettingsHandlers.clear();
5063
5064
    if (g.LogFile)
5065
    {
5066
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
5067
        if (g.LogFile != stdout)
5068
#endif
5069
            ImFileClose(g.LogFile);
5070
        g.LogFile = NULL;
5071
    }
5072
    g.LogBuffer.clear();
5073
    g.DebugLogBuf.clear();
5074
    g.DebugLogIndex.clear();
5075
5076
    g.Initialized = false;
5077
}
5078
5079
// FIXME: Add a more explicit sort order in the window structure.
5080
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5081
{
5082
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5083
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5084
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5085
        return d;
5086
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5087
        return d;
5088
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5089
}
5090
5091
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5092
{
5093
    out_sorted_windows->push_back(window);
5094
    if (window->Active)
5095
    {
5096
        int count = window->DC.ChildWindows.Size;
5097
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5098
        for (int i = 0; i < count; i++)
5099
        {
5100
            ImGuiWindow* child = window->DC.ChildWindows[i];
5101
            if (child->Active)
5102
                AddWindowToSortBuffer(out_sorted_windows, child);
5103
        }
5104
    }
5105
}
5106
5107
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
5108
{
5109
    if (draw_list->CmdBuffer.Size == 0)
5110
        return;
5111
    if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL)
5112
        return;
5113
5114
    // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
5115
    // May trigger for you if you are using PrimXXX functions incorrectly.
5116
    IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
5117
    IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
5118
    if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
5119
        IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
5120
5121
    // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
5122
    // If this assert triggers because you are drawing lots of stuff manually:
5123
    // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
5124
    //   Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
5125
    // - If you want large meshes with more than 64K vertices, you can either:
5126
    //   (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
5127
    //       Most example backends already support this from 1.71. Pre-1.71 backends won't.
5128
    //       Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
5129
    //   (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
5130
    //       Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
5131
    //         glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
5132
    //       Your own engine or render API may use different parameters or function calls to specify index sizes.
5133
    //       2 and 4 bytes indices are generally supported by most graphics API.
5134
    // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
5135
    //   the 64K limit to split your draw commands in multiple draw lists.
5136
    if (sizeof(ImDrawIdx) == 2)
5137
        IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
5138
5139
    out_list->push_back(draw_list);
5140
}
5141
5142
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5143
{
5144
    ImGuiContext& g = *GImGui;
5145
    ImGuiViewportP* viewport = window->Viewport;
5146
    g.IO.MetricsRenderWindows++;
5147
    if (window->Flags & ImGuiWindowFlags_DockNodeHost)
5148
        window->DrawList->ChannelsMerge();
5149
    AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5150
    for (int i = 0; i < window->DC.ChildWindows.Size; i++)
5151
    {
5152
        ImGuiWindow* child = window->DC.ChildWindows[i];
5153
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5154
            AddWindowToDrawData(child, layer);
5155
    }
5156
}
5157
5158
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5159
{
5160
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5161
}
5162
5163
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5164
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5165
{
5166
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5167
}
5168
5169
void ImDrawDataBuilder::FlattenIntoSingleLayer()
5170
{
5171
    int n = Layers[0].Size;
5172
    int size = n;
5173
    for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
5174
        size += Layers[i].Size;
5175
    Layers[0].resize(size);
5176
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
5177
    {
5178
        ImVector<ImDrawList*>& layer = Layers[layer_n];
5179
        if (layer.empty())
5180
            continue;
5181
        memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
5182
        n += layer.Size;
5183
        layer.resize(0);
5184
    }
5185
}
5186
5187
static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
5188
{
5189
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5190
    // and to allow applications/backends to easily skip rendering.
5191
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5192
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5193
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5194
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_Minimized) != 0;
5195
5196
    ImGuiIO& io = ImGui::GetIO();
5197
    ImDrawData* draw_data = &viewport->DrawDataP;
5198
    viewport->DrawData = draw_data; // Make publicly accessible
5199
    draw_data->Valid = true;
5200
    draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
5201
    draw_data->CmdListsCount = draw_lists->Size;
5202
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5203
    draw_data->DisplayPos = viewport->Pos;
5204
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5205
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5206
    draw_data->OwnerViewport = viewport;
5207
    for (int n = 0; n < draw_lists->Size; n++)
5208
    {
5209
        ImDrawList* draw_list = draw_lists->Data[n];
5210
        draw_list->_PopUnusedDrawCmd();
5211
        draw_data->TotalVtxCount += draw_list->VtxBuffer.Size;
5212
        draw_data->TotalIdxCount += draw_list->IdxBuffer.Size;
5213
    }
5214
}
5215
5216
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5217
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5218
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5219
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5220
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5221
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5222
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5223
{
5224
    ImGuiWindow* window = GetCurrentWindow();
5225
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5226
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5227
}
5228
5229
void ImGui::PopClipRect()
5230
{
5231
    ImGuiWindow* window = GetCurrentWindow();
5232
    window->DrawList->PopClipRect();
5233
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5234
}
5235
5236
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5237
{
5238
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5239
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5240
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5241
    return window;
5242
}
5243
5244
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5245
{
5246
    if ((col & IM_COL32_A_MASK) == 0)
5247
        return;
5248
5249
    ImGuiViewportP* viewport = window->Viewport;
5250
    ImRect viewport_rect = viewport->GetMainRect();
5251
5252
    // Draw behind window by moving the draw command at the FRONT of the draw list
5253
    {
5254
        // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
5255
        // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5256
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5257
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5258
        if (draw_list->CmdBuffer.Size == 0)
5259
            draw_list->AddDrawCmd();
5260
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // Ensure ImDrawCmd are not merged
5261
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5262
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5263
        IM_ASSERT(cmd.ElemCount == 6);
5264
        draw_list->CmdBuffer.pop_back();
5265
        draw_list->CmdBuffer.push_front(cmd);
5266
        draw_list->PopClipRect();
5267
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5268
    }
5269
5270
    // Draw over sibling docking nodes in a same docking tree
5271
    if (window->RootWindow->DockIsActive)
5272
    {
5273
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5274
        if (draw_list->CmdBuffer.Size == 0)
5275
            draw_list->AddDrawCmd();
5276
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5277
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5278
        draw_list->PopClipRect();
5279
    }
5280
}
5281
5282
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5283
{
5284
    ImGuiContext& g = *GImGui;
5285
    ImGuiWindow* bottom_most_visible_window = parent_window;
5286
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5287
    {
5288
        ImGuiWindow* window = g.Windows[i];
5289
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5290
            continue;
5291
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5292
            break;
5293
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5294
            bottom_most_visible_window = window;
5295
    }
5296
    return bottom_most_visible_window;
5297
}
5298
5299
static void ImGui::RenderDimmedBackgrounds()
5300
{
5301
    ImGuiContext& g = *GImGui;
5302
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5303
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5304
        return;
5305
    const bool dim_bg_for_modal = (modal_window != NULL);
5306
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5307
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5308
        return;
5309
5310
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5311
    if (dim_bg_for_modal)
5312
    {
5313
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5314
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5315
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
5316
        viewports_already_dimmed[0] = modal_window->Viewport;
5317
    }
5318
    else if (dim_bg_for_window_list)
5319
    {
5320
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5321
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5322
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5323
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5324
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5325
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5326
5327
        // Draw border around CTRL+Tab target window
5328
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5329
        ImGuiViewport* viewport = window->Viewport;
5330
        float distance = g.FontSize;
5331
        ImRect bb = window->Rect();
5332
        bb.Expand(distance);
5333
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5334
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5335
        if (window->DrawList->CmdBuffer.Size == 0)
5336
            window->DrawList->AddDrawCmd();
5337
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5338
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5339
        window->DrawList->PopClipRect();
5340
    }
5341
5342
    // Draw dimming background on _other_ viewports than the ones our windows are in
5343
    for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
5344
    {
5345
        ImGuiViewportP* viewport = g.Viewports[viewport_n];
5346
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5347
            continue;
5348
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5349
            continue;
5350
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5351
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5352
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5353
    }
5354
}
5355
5356
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5357
void ImGui::EndFrame()
5358
{
5359
    ImGuiContext& g = *GImGui;
5360
    IM_ASSERT(g.Initialized);
5361
5362
    // Don't process EndFrame() multiple times.
5363
    if (g.FrameCountEnded == g.FrameCount)
5364
        return;
5365
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5366
5367
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5368
5369
    ErrorCheckEndFrameSanityChecks();
5370
5371
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5372
    if (g.IO.SetPlatformImeDataFn && memcmp(&g.PlatformImeData, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5373
    {
5374
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5375
        g.IO.SetPlatformImeDataFn(viewport ? viewport : GetMainViewport(), &g.PlatformImeData);
5376
    }
5377
5378
    // Hide implicit/fallback "Debug" window if it hasn't been used
5379
    g.WithinFrameScopeWithImplicitWindow = false;
5380
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5381
        g.CurrentWindow->Active = false;
5382
    End();
5383
5384
    // Update navigation: CTRL+Tab, wrap-around requests
5385
    NavEndFrame();
5386
5387
    // Update docking
5388
    DockContextEndFrame(&g);
5389
5390
    SetCurrentViewport(NULL, NULL);
5391
5392
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5393
    if (g.DragDropActive)
5394
    {
5395
        bool is_delivered = g.DragDropPayload.Delivery;
5396
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5397
        if (is_delivered || is_elapsed)
5398
            ClearDragDrop();
5399
    }
5400
5401
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5402
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5403
    {
5404
        g.DragDropWithinSource = true;
5405
        SetTooltip("...");
5406
        g.DragDropWithinSource = false;
5407
    }
5408
5409
    // End frame
5410
    g.WithinFrameScope = false;
5411
    g.FrameCountEnded = g.FrameCount;
5412
5413
    // Initiate moving window + handle left-click and right-click focus
5414
    UpdateMouseMovingWindowEndFrame();
5415
5416
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5417
    UpdateViewportsEndFrame();
5418
5419
    // Sort the window list so that all child windows are after their parent
5420
    // We cannot do that on FocusWindow() because children may not exist yet
5421
    g.WindowsTempSortBuffer.resize(0);
5422
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5423
    for (int i = 0; i != g.Windows.Size; i++)
5424
    {
5425
        ImGuiWindow* window = g.Windows[i];
5426
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5427
            continue;
5428
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5429
    }
5430
5431
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5432
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5433
    g.Windows.swap(g.WindowsTempSortBuffer);
5434
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5435
5436
    // Unlock font atlas
5437
    g.IO.Fonts->Locked = false;
5438
5439
    // Clear Input data for next frame
5440
    g.IO.AppFocusLost = false;
5441
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5442
    g.IO.InputQueueCharacters.resize(0);
5443
5444
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5445
}
5446
5447
// Prepare the data for rendering so you can call GetDrawData()
5448
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5449
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5450
void ImGui::Render()
5451
{
5452
    ImGuiContext& g = *GImGui;
5453
    IM_ASSERT(g.Initialized);
5454
5455
    if (g.FrameCountEnded != g.FrameCount)
5456
        EndFrame();
5457
    const bool first_render_of_frame = (g.FrameCountRendered != g.FrameCount);
5458
    g.FrameCountRendered = g.FrameCount;
5459
    g.IO.MetricsRenderWindows = 0;
5460
5461
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5462
5463
    // Add background ImDrawList (for each active viewport)
5464
    for (int n = 0; n != g.Viewports.Size; n++)
5465
    {
5466
        ImGuiViewportP* viewport = g.Viewports[n];
5467
        viewport->DrawDataBuilder.Clear();
5468
        if (viewport->DrawLists[0] != NULL)
5469
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5470
    }
5471
5472
    // Add ImDrawList to render
5473
    ImGuiWindow* windows_to_render_top_most[2];
5474
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5475
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5476
    for (int n = 0; n != g.Windows.Size; n++)
5477
    {
5478
        ImGuiWindow* window = g.Windows[n];
5479
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5480
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5481
            AddRootWindowToDrawData(window);
5482
    }
5483
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5484
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5485
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5486
5487
    // Draw modal/window whitening backgrounds
5488
    if (first_render_of_frame)
5489
        RenderDimmedBackgrounds();
5490
5491
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5492
    if (g.IO.MouseDrawCursor && first_render_of_frame && g.MouseCursor != ImGuiMouseCursor_None)
5493
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5494
5495
    // Setup ImDrawData structures for end-user
5496
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5497
    for (int n = 0; n < g.Viewports.Size; n++)
5498
    {
5499
        ImGuiViewportP* viewport = g.Viewports[n];
5500
        viewport->DrawDataBuilder.FlattenIntoSingleLayer();
5501
5502
        // Add foreground ImDrawList (for each active viewport)
5503
        if (viewport->DrawLists[1] != NULL)
5504
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5505
5506
        SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
5507
        ImDrawData* draw_data = viewport->DrawData;
5508
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5509
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5510
    }
5511
5512
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5513
}
5514
5515
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5516
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5517
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5518
{
5519
    ImGuiContext& g = *GImGui;
5520
5521
    const char* text_display_end;
5522
    if (hide_text_after_double_hash)
5523
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5524
    else
5525
        text_display_end = text_end;
5526
5527
    ImFont* font = g.Font;
5528
    const float font_size = g.FontSize;
5529
    if (text == text_display_end)
5530
        return ImVec2(0.0f, font_size);
5531
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5532
5533
    // Round
5534
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5535
    // FIXME: Investigate using ceilf or e.g.
5536
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5537
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5538
    text_size.x = IM_FLOOR(text_size.x + 0.99999f);
5539
5540
    return text_size;
5541
}
5542
5543
// Find window given position, search front-to-back
5544
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5545
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5546
// called, aka before the next Begin(). Moving window isn't affected.
5547
static void FindHoveredWindow()
5548
{
5549
    ImGuiContext& g = *GImGui;
5550
5551
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5552
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5553
    if (g.MovingWindow)
5554
        g.MovingWindow->Viewport = g.MouseViewport;
5555
5556
    ImGuiWindow* hovered_window = NULL;
5557
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5558
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5559
        hovered_window = g.MovingWindow;
5560
5561
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5562
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5563
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5564
    {
5565
        ImGuiWindow* window = g.Windows[i];
5566
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5567
        if (!window->Active || window->Hidden)
5568
            continue;
5569
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5570
            continue;
5571
        IM_ASSERT(window->Viewport);
5572
        if (window->Viewport != g.MouseViewport)
5573
            continue;
5574
5575
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5576
        ImRect bb(window->OuterRectClipped);
5577
        if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
5578
            bb.Expand(padding_regular);
5579
        else
5580
            bb.Expand(padding_for_resize);
5581
        if (!bb.Contains(g.IO.MousePos))
5582
            continue;
5583
5584
        // Support for one rectangular hole in any given window
5585
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5586
        if (window->HitTestHoleSize.x != 0)
5587
        {
5588
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5589
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5590
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5591
                continue;
5592
        }
5593
5594
        if (hovered_window == NULL)
5595
            hovered_window = window;
5596
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5597
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5598
            hovered_window_ignoring_moving_window = window;
5599
        if (hovered_window && hovered_window_ignoring_moving_window)
5600
            break;
5601
    }
5602
5603
    g.HoveredWindow = hovered_window;
5604
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5605
5606
    if (g.MovingWindow)
5607
        g.MovingWindow->Viewport = moving_window_viewport;
5608
}
5609
5610
bool ImGui::IsItemActive()
5611
{
5612
    ImGuiContext& g = *GImGui;
5613
    if (g.ActiveId)
5614
        return g.ActiveId == g.LastItemData.ID;
5615
    return false;
5616
}
5617
5618
bool ImGui::IsItemActivated()
5619
{
5620
    ImGuiContext& g = *GImGui;
5621
    if (g.ActiveId)
5622
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5623
            return true;
5624
    return false;
5625
}
5626
5627
bool ImGui::IsItemDeactivated()
5628
{
5629
    ImGuiContext& g = *GImGui;
5630
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5631
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5632
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5633
}
5634
5635
bool ImGui::IsItemDeactivatedAfterEdit()
5636
{
5637
    ImGuiContext& g = *GImGui;
5638
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5639
}
5640
5641
// == GetItemID() == GetFocusID()
5642
bool ImGui::IsItemFocused()
5643
{
5644
    ImGuiContext& g = *GImGui;
5645
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5646
        return false;
5647
5648
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5649
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5650
    ImGuiWindow* window = g.CurrentWindow;
5651
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5652
        return false;
5653
5654
    return true;
5655
}
5656
5657
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5658
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5659
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5660
{
5661
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5662
}
5663
5664
bool ImGui::IsItemToggledOpen()
5665
{
5666
    ImGuiContext& g = *GImGui;
5667
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5668
}
5669
5670
bool ImGui::IsItemToggledSelection()
5671
{
5672
    ImGuiContext& g = *GImGui;
5673
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5674
}
5675
5676
bool ImGui::IsAnyItemHovered()
5677
{
5678
    ImGuiContext& g = *GImGui;
5679
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5680
}
5681
5682
bool ImGui::IsAnyItemActive()
5683
{
5684
    ImGuiContext& g = *GImGui;
5685
    return g.ActiveId != 0;
5686
}
5687
5688
bool ImGui::IsAnyItemFocused()
5689
{
5690
    ImGuiContext& g = *GImGui;
5691
    return g.NavId != 0 && !g.NavDisableHighlight;
5692
}
5693
5694
bool ImGui::IsItemVisible()
5695
{
5696
    ImGuiContext& g = *GImGui;
5697
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5698
}
5699
5700
bool ImGui::IsItemEdited()
5701
{
5702
    ImGuiContext& g = *GImGui;
5703
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5704
}
5705
5706
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5707
// FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
5708
void ImGui::SetItemAllowOverlap()
5709
{
5710
    ImGuiContext& g = *GImGui;
5711
    ImGuiID id = g.LastItemData.ID;
5712
    if (g.HoveredId == id)
5713
        g.HoveredIdAllowOverlap = true;
5714
    if (g.ActiveId == id)
5715
        g.ActiveIdAllowOverlap = true;
5716
}
5717
5718
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5719
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5720
{
5721
    ImGuiContext& g = *GImGui;
5722
    IM_ASSERT(g.ActiveId != 0);
5723
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5724
    g.ActiveIdUsingAllKeyboardKeys = true;
5725
    NavMoveRequestCancel();
5726
}
5727
5728
ImVec2 ImGui::GetItemRectMin()
5729
{
5730
    ImGuiContext& g = *GImGui;
5731
    return g.LastItemData.Rect.Min;
5732
}
5733
5734
ImVec2 ImGui::GetItemRectMax()
5735
{
5736
    ImGuiContext& g = *GImGui;
5737
    return g.LastItemData.Rect.Max;
5738
}
5739
5740
ImVec2 ImGui::GetItemRectSize()
5741
{
5742
    ImGuiContext& g = *GImGui;
5743
    return g.LastItemData.Rect.GetSize();
5744
}
5745
5746
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
5747
{
5748
    ImGuiContext& g = *GImGui;
5749
    ImGuiWindow* parent_window = g.CurrentWindow;
5750
5751
    flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoDocking;
5752
    flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove);  // Inherit the NoMove flag
5753
5754
    // Size
5755
    const ImVec2 content_avail = GetContentRegionAvail();
5756
    ImVec2 size = ImFloor(size_arg);
5757
    const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
5758
    if (size.x <= 0.0f)
5759
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too many issues)
5760
    if (size.y <= 0.0f)
5761
        size.y = ImMax(content_avail.y + size.y, 4.0f);
5762
    SetNextWindowSize(size);
5763
5764
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5765
    const char* temp_window_name;
5766
    if (name)
5767
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5768
    else
5769
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5770
5771
    const float backup_border_size = g.Style.ChildBorderSize;
5772
    if (!border)
5773
        g.Style.ChildBorderSize = 0.0f;
5774
    bool ret = Begin(temp_window_name, NULL, flags);
5775
    g.Style.ChildBorderSize = backup_border_size;
5776
5777
    ImGuiWindow* child_window = g.CurrentWindow;
5778
    child_window->ChildId = id;
5779
    child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
5780
5781
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5782
    // While this is not really documented/defined, it seems that the expected thing to do.
5783
    if (child_window->BeginCount == 1)
5784
        parent_window->DC.CursorPos = child_window->Pos;
5785
5786
    // Process navigation-in immediately so NavInit can run on first frame
5787
    if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavHasScroll))
5788
    {
5789
        FocusWindow(child_window);
5790
        NavInitWindow(child_window, false);
5791
        SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5792
        g.ActiveIdSource = ImGuiInputSource_Nav;
5793
    }
5794
    return ret;
5795
}
5796
5797
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5798
{
5799
    ImGuiWindow* window = GetCurrentWindow();
5800
    return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
5801
}
5802
5803
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5804
{
5805
    IM_ASSERT(id != 0);
5806
    return BeginChildEx(NULL, id, size_arg, border, extra_flags);
5807
}
5808
5809
void ImGui::EndChild()
5810
{
5811
    ImGuiContext& g = *GImGui;
5812
    ImGuiWindow* window = g.CurrentWindow;
5813
5814
    IM_ASSERT(g.WithinEndChild == false);
5815
    IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5816
5817
    g.WithinEndChild = true;
5818
    if (window->BeginCount > 1)
5819
    {
5820
        End();
5821
    }
5822
    else
5823
    {
5824
        ImVec2 sz = window->Size;
5825
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
5826
            sz.x = ImMax(4.0f, sz.x);
5827
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
5828
            sz.y = ImMax(4.0f, sz.y);
5829
        End();
5830
5831
        ImGuiWindow* parent_window = g.CurrentWindow;
5832
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
5833
        ItemSize(sz);
5834
        if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
5835
        {
5836
            ItemAdd(bb, window->ChildId);
5837
            RenderNavHighlight(bb, window->ChildId);
5838
5839
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5840
            if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
5841
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5842
        }
5843
        else
5844
        {
5845
            // Not navigable into
5846
            ItemAdd(bb, 0);
5847
        }
5848
        if (g.HoveredWindow == window)
5849
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5850
    }
5851
    g.WithinEndChild = false;
5852
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5853
}
5854
5855
// Helper to create a child window / scrolling region that looks like a normal widget frame.
5856
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
5857
{
5858
    ImGuiContext& g = *GImGui;
5859
    const ImGuiStyle& style = g.Style;
5860
    PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
5861
    PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
5862
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
5863
    PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
5864
    bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
5865
    PopStyleVar(3);
5866
    PopStyleColor();
5867
    return ret;
5868
}
5869
5870
void ImGui::EndChildFrame()
5871
{
5872
    EndChild();
5873
}
5874
5875
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5876
{
5877
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5878
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5879
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5880
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5881
}
5882
5883
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5884
{
5885
    ImGuiContext& g = *GImGui;
5886
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5887
}
5888
5889
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5890
{
5891
    ImGuiID id = ImHashStr(name);
5892
    return FindWindowByID(id);
5893
}
5894
5895
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5896
{
5897
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5898
    window->ViewportPos = main_viewport->Pos;
5899
    if (settings->ViewportId)
5900
    {
5901
        window->ViewportId = settings->ViewportId;
5902
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5903
    }
5904
    window->Pos = ImFloor(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5905
    if (settings->Size.x > 0 && settings->Size.y > 0)
5906
        window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
5907
    window->Collapsed = settings->Collapsed;
5908
    window->DockId = settings->DockId;
5909
    window->DockOrder = settings->DockOrder;
5910
}
5911
5912
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5913
{
5914
    ImGuiContext& g = *GImGui;
5915
5916
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5917
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5918
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5919
    {
5920
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5921
        g.WindowsFocusOrder.push_back(window);
5922
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5923
    }
5924
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5925
    {
5926
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5927
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5928
            g.WindowsFocusOrder[n]->FocusOrder--;
5929
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5930
        window->FocusOrder = -1;
5931
    }
5932
    window->IsExplicitChild = new_is_explicit_child;
5933
}
5934
5935
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5936
{
5937
    ImGuiContext& g = *GImGui;
5938
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5939
5940
    // Create window the first time
5941
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5942
    window->Flags = flags;
5943
    g.WindowsById.SetVoidPtr(window->ID, window);
5944
5945
    // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5946
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5947
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5948
    window->ViewportPos = main_viewport->Pos;
5949
5950
    // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
5951
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5952
        if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
5953
        {
5954
            // Retrieve settings from .ini file
5955
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5956
            SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5957
            ApplyWindowSettings(window, settings);
5958
        }
5959
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5960
5961
    if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5962
    {
5963
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5964
        window->AutoFitOnlyGrows = false;
5965
    }
5966
    else
5967
    {
5968
        if (window->Size.x <= 0.0f)
5969
            window->AutoFitFramesX = 2;
5970
        if (window->Size.y <= 0.0f)
5971
            window->AutoFitFramesY = 2;
5972
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5973
    }
5974
5975
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5976
        g.Windows.push_front(window); // Quite slow but rare and only once
5977
    else
5978
        g.Windows.push_back(window);
5979
5980
    return window;
5981
}
5982
5983
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5984
{
5985
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5986
}
5987
5988
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5989
{
5990
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5991
}
5992
5993
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5994
{
5995
    ImGuiContext& g = *GImGui;
5996
    ImVec2 new_size = size_desired;
5997
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5998
    {
5999
        // Using -1,-1 on either X/Y axis to preserve the current size.
6000
        ImRect cr = g.NextWindowData.SizeConstraintRect;
6001
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6002
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6003
        if (g.NextWindowData.SizeCallback)
6004
        {
6005
            ImGuiSizeCallbackData data;
6006
            data.UserData = g.NextWindowData.SizeCallbackUserData;
6007
            data.Pos = window->Pos;
6008
            data.CurrentSize = window->SizeFull;
6009
            data.DesiredSize = new_size;
6010
            g.NextWindowData.SizeCallback(&data);
6011
            new_size = data.DesiredSize;
6012
        }
6013
        new_size.x = IM_FLOOR(new_size.x);
6014
        new_size.y = IM_FLOOR(new_size.y);
6015
    }
6016
6017
    // Minimum size
6018
    if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
6019
    {
6020
        ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
6021
        const float decoration_up_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight();
6022
        new_size = ImMax(new_size, g.Style.WindowMinSize);
6023
        new_size.y = ImMax(new_size.y, decoration_up_height + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
6024
    }
6025
    return new_size;
6026
}
6027
6028
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6029
{
6030
    bool preserve_old_content_sizes = false;
6031
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6032
        preserve_old_content_sizes = true;
6033
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6034
        preserve_old_content_sizes = true;
6035
    if (preserve_old_content_sizes)
6036
    {
6037
        *content_size_current = window->ContentSize;
6038
        *content_size_ideal = window->ContentSizeIdeal;
6039
        return;
6040
    }
6041
6042
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6043
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6044
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6045
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6046
}
6047
6048
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6049
{
6050
    ImGuiContext& g = *GImGui;
6051
    ImGuiStyle& style = g.Style;
6052
    const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
6053
    ImVec2 size_pad = window->WindowPadding * 2.0f;
6054
    ImVec2 size_desired = size_contents + size_pad + ImVec2(0.0f, decoration_up_height);
6055
    if (window->Flags & ImGuiWindowFlags_Tooltip)
6056
    {
6057
        // Tooltip always resize
6058
        return size_desired;
6059
    }
6060
    else
6061
    {
6062
        // Maximum window size is determined by the viewport size or monitor size
6063
        const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
6064
        const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
6065
        ImVec2 size_min = style.WindowMinSize;
6066
        if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6067
            size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
6068
6069
        ImVec2 avail_size = window->Viewport->WorkSize;
6070
        if (window->ViewportOwned)
6071
            avail_size = ImVec2(FLT_MAX, FLT_MAX);
6072
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6073
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
6074
            avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
6075
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
6076
6077
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6078
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6079
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6080
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - 0.0f                 < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6081
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_up_height < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6082
        if (will_have_scrollbar_x)
6083
            size_auto_fit.y += style.ScrollbarSize;
6084
        if (will_have_scrollbar_y)
6085
            size_auto_fit.x += style.ScrollbarSize;
6086
        return size_auto_fit;
6087
    }
6088
}
6089
6090
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6091
{
6092
    ImVec2 size_contents_current;
6093
    ImVec2 size_contents_ideal;
6094
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6095
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6096
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6097
    return size_final;
6098
}
6099
6100
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6101
{
6102
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6103
        return ImGuiCol_PopupBg;
6104
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6105
        return ImGuiCol_ChildBg;
6106
    return ImGuiCol_WindowBg;
6107
}
6108
6109
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6110
{
6111
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6112
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6113
    ImVec2 size_expected = pos_max - pos_min;
6114
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6115
    *out_pos = pos_min;
6116
    if (corner_norm.x == 0.0f)
6117
        out_pos->x -= (size_constrained.x - size_expected.x);
6118
    if (corner_norm.y == 0.0f)
6119
        out_pos->y -= (size_constrained.y - size_expected.y);
6120
    *out_size = size_constrained;
6121
}
6122
6123
// Data for resizing from corner
6124
struct ImGuiResizeGripDef
6125
{
6126
    ImVec2  CornerPosN;
6127
    ImVec2  InnerDir;
6128
    int     AngleMin12, AngleMax12;
6129
};
6130
static const ImGuiResizeGripDef resize_grip_def[4] =
6131
{
6132
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6133
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6134
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6135
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6136
};
6137
6138
// Data for resizing from borders
6139
struct ImGuiResizeBorderDef
6140
{
6141
    ImVec2 InnerDir;
6142
    ImVec2 SegmentN1, SegmentN2;
6143
    float  OuterAngle;
6144
};
6145
static const ImGuiResizeBorderDef resize_border_def[4] =
6146
{
6147
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6148
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6149
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6150
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6151
};
6152
6153
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6154
{
6155
    ImRect rect = window->Rect();
6156
    if (thickness == 0.0f)
6157
        rect.Max -= ImVec2(1, 1);
6158
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6159
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6160
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6161
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6162
    IM_ASSERT(0);
6163
    return ImRect();
6164
}
6165
6166
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6167
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6168
{
6169
    IM_ASSERT(n >= 0 && n < 4);
6170
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6171
    id = ImHashStr("#RESIZE", 0, id);
6172
    id = ImHashData(&n, sizeof(int), id);
6173
    return id;
6174
}
6175
6176
// Borders (Left, Right, Up, Down)
6177
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6178
{
6179
    IM_ASSERT(dir >= 0 && dir < 4);
6180
    int n = (int)dir + 4;
6181
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6182
    id = ImHashStr("#RESIZE", 0, id);
6183
    id = ImHashData(&n, sizeof(int), id);
6184
    return id;
6185
}
6186
6187
// Handle resize for: Resize Grips, Borders, Gamepad
6188
// Return true when using auto-fit (double-click on resize grip)
6189
static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6190
{
6191
    ImGuiContext& g = *GImGui;
6192
    ImGuiWindowFlags flags = window->Flags;
6193
6194
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6195
        return false;
6196
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6197
        return false;
6198
6199
    bool ret_auto_fit = false;
6200
    const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
6201
    const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6202
    const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
6203
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6204
6205
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6206
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6207
6208
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6209
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6210
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6211
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6212
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6213
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6214
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6215
    if (clip_with_viewport_rect)
6216
        window->ClipRect = window->Viewport->GetMainRect();
6217
6218
    // Resize grips and borders are on layer 1
6219
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6220
6221
    // Manual resize grips
6222
    PushID("#RESIZE");
6223
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6224
    {
6225
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6226
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6227
6228
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6229
        bool hovered, held;
6230
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6231
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6232
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6233
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6234
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6235
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6236
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6237
        if (hovered || held)
6238
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6239
6240
        if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0)
6241
        {
6242
            // Manual auto-fit when double-clicking
6243
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6244
            ret_auto_fit = true;
6245
            ClearActiveID();
6246
        }
6247
        else if (held)
6248
        {
6249
            // Resize from any of the four corners
6250
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6251
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, def.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);
6252
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);
6253
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6254
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6255
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6256
        }
6257
6258
        // Only lower-left grip is visible before hovering/activating
6259
        if (resize_grip_n == 0 || held || hovered)
6260
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6261
    }
6262
    for (int border_n = 0; border_n < resize_border_count; border_n++)
6263
    {
6264
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6265
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6266
6267
        bool hovered, held;
6268
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6269
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6270
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6271
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6272
        //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6273
        if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
6274
        {
6275
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6276
            if (held)
6277
                *border_held = border_n;
6278
        }
6279
        if (held)
6280
        {
6281
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX);
6282
            ImVec2 clamp_max(border_n == ImGuiDir_Left  ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up   ? visibility_rect.Max.y : +FLT_MAX);
6283
            ImVec2 border_target = window->Pos;
6284
            border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
6285
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6286
            CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6287
        }
6288
    }
6289
    PopID();
6290
6291
    // Restore nav layer
6292
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6293
6294
    // Navigation resize (keyboard/gamepad)
6295
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6296
    // Not even sure the callback works here.
6297
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6298
    {
6299
        ImVec2 nav_resize_dir;
6300
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6301
            nav_resize_dir = GetKeyVector2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6302
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6303
            nav_resize_dir = GetKeyVector2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6304
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6305
        {
6306
            const float NAV_RESIZE_SPEED = 600.0f;
6307
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6308
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6309
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, visibility_rect.Min - window->Pos - window->Size); // We need Pos+Size >= visibility_rect.Min, so Size >= visibility_rect.Min - Pos, so size_delta >= visibility_rect.Min - window->Pos - window->Size
6310
            g.NavWindowingToggleLayer = false;
6311
            g.NavDisableMouseHover = true;
6312
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6313
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaSize);
6314
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6315
            {
6316
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6317
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6318
                g.NavWindowingAccumDeltaSize -= accum_floored;
6319
            }
6320
        }
6321
    }
6322
6323
    // Apply back modified position/size to window
6324
    if (size_target.x != FLT_MAX)
6325
    {
6326
        window->SizeFull = size_target;
6327
        MarkIniSettingsDirty(window);
6328
    }
6329
    if (pos_target.x != FLT_MAX)
6330
    {
6331
        window->Pos = ImFloor(pos_target);
6332
        MarkIniSettingsDirty(window);
6333
    }
6334
6335
    window->Size = window->SizeFull;
6336
    return ret_auto_fit;
6337
}
6338
6339
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6340
{
6341
    ImGuiContext& g = *GImGui;
6342
    ImVec2 size_for_clamping = window->Size;
6343
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6344
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6345
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6346
}
6347
6348
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6349
{
6350
    ImGuiContext& g = *GImGui;
6351
    float rounding = window->WindowRounding;
6352
    float border_size = window->WindowBorderSize;
6353
    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
6354
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
6355
6356
    int border_held = window->ResizeBorderHeld;
6357
    if (border_held != -1)
6358
    {
6359
        const ImGuiResizeBorderDef& def = resize_border_def[border_held];
6360
        ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
6361
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6362
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6363
        window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
6364
    }
6365
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6366
    {
6367
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6368
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
6369
    }
6370
}
6371
6372
// Draw background and borders
6373
// Draw and handle scrollbars
6374
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6375
{
6376
    ImGuiContext& g = *GImGui;
6377
    ImGuiStyle& style = g.Style;
6378
    ImGuiWindowFlags flags = window->Flags;
6379
6380
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6381
    IM_ASSERT(window->BeginCount == 0);
6382
    window->SkipItems = false;
6383
6384
    // Draw window + handle manual resize
6385
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6386
    const float window_rounding = window->WindowRounding;
6387
    const float window_border_size = window->WindowBorderSize;
6388
    if (window->Collapsed)
6389
    {
6390
        // Title bar only
6391
        const float backup_border_size = style.FrameBorderSize;
6392
        g.Style.FrameBorderSize = window->WindowBorderSize;
6393
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6394
        if (window->ViewportOwned)
6395
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6396
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6397
        g.Style.FrameBorderSize = backup_border_size;
6398
    }
6399
    else
6400
    {
6401
        // Window background
6402
        if (!(flags & ImGuiWindowFlags_NoBackground))
6403
        {
6404
            bool is_docking_transparent_payload = false;
6405
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6406
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6407
                    is_docking_transparent_payload = true;
6408
6409
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6410
            if (window->ViewportOwned)
6411
            {
6412
                bg_col |= IM_COL32_A_MASK; // No alpha
6413
                if (is_docking_transparent_payload)
6414
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6415
            }
6416
            else
6417
            {
6418
                // Adjust alpha. For docking
6419
                bool override_alpha = false;
6420
                float alpha = 1.0f;
6421
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6422
                {
6423
                    alpha = g.NextWindowData.BgAlphaVal;
6424
                    override_alpha = true;
6425
                }
6426
                if (is_docking_transparent_payload)
6427
                {
6428
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6429
                    override_alpha = true;
6430
                }
6431
                if (override_alpha)
6432
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6433
            }
6434
6435
            // Render, for docked windows and host windows we ensure bg goes before decorations
6436
            if (window->DockIsActive)
6437
                window->DockNode->LastBgColor = bg_col;
6438
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6439
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6440
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6441
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6442
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6443
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6444
        }
6445
        if (window->DockIsActive)
6446
            window->DockNode->IsBgDrawnThisFrame = true;
6447
6448
        // Title bar
6449
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6450
        // in order for their pos/size to be matching their undocking state.)
6451
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6452
        {
6453
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6454
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6455
        }
6456
6457
        // Menu bar
6458
        if (flags & ImGuiWindowFlags_MenuBar)
6459
        {
6460
            ImRect menu_bar_rect = window->MenuBarRect();
6461
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6462
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6463
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6464
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6465
        }
6466
6467
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6468
        ImGuiDockNode* node = window->DockNode;
6469
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6470
        {
6471
            float unhide_sz_draw = ImFloor(g.FontSize * 0.70f);
6472
            float unhide_sz_hit = ImFloor(g.FontSize * 0.55f);
6473
            ImVec2 p = node->Pos;
6474
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6475
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6476
            KeepAliveID(unhide_id);
6477
            bool hovered, held;
6478
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6479
                node->WantHiddenTabBarToggle = true;
6480
            else if (held && IsMouseDragging(0))
6481
                StartMouseMovingWindowOrNode(window, node, true);
6482
6483
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6484
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6485
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6486
        }
6487
6488
        // Scrollbars
6489
        if (window->ScrollbarX)
6490
            Scrollbar(ImGuiAxis_X);
6491
        if (window->ScrollbarY)
6492
            Scrollbar(ImGuiAxis_Y);
6493
6494
        // Render resize grips (after their input handling so we don't have a frame of latency)
6495
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6496
        {
6497
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6498
            {
6499
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6500
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6501
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6502
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6503
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6504
                window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
6505
            }
6506
        }
6507
6508
        // Borders (for dock node host they will be rendered over after the tab bar)
6509
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6510
            RenderWindowOuterBorders(window);
6511
    }
6512
}
6513
6514
// Render title text, collapse button, close button
6515
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6516
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6517
{
6518
    ImGuiContext& g = *GImGui;
6519
    ImGuiStyle& style = g.Style;
6520
    ImGuiWindowFlags flags = window->Flags;
6521
6522
    const bool has_close_button = (p_open != NULL);
6523
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6524
6525
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6526
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6527
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6528
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6529
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6530
6531
    // Layout buttons
6532
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6533
    float pad_l = style.FramePadding.x;
6534
    float pad_r = style.FramePadding.x;
6535
    float button_sz = g.FontSize;
6536
    ImVec2 close_button_pos;
6537
    ImVec2 collapse_button_pos;
6538
    if (has_close_button)
6539
    {
6540
        pad_r += button_sz;
6541
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6542
    }
6543
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6544
    {
6545
        pad_r += button_sz;
6546
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6547
    }
6548
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6549
    {
6550
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
6551
        pad_l += button_sz;
6552
    }
6553
6554
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6555
    if (has_collapse_button)
6556
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6557
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6558
6559
    // Close button
6560
    if (has_close_button)
6561
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6562
            *p_open = false;
6563
6564
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6565
    g.CurrentItemFlags = item_flags_backup;
6566
6567
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6568
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6569
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6570
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6571
6572
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6573
    // while uncentered title text will still reach edges correctly.
6574
    if (pad_l > style.FramePadding.x)
6575
        pad_l += g.Style.ItemInnerSpacing.x;
6576
    if (pad_r > style.FramePadding.x)
6577
        pad_r += g.Style.ItemInnerSpacing.x;
6578
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6579
    {
6580
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6581
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6582
        pad_l = ImMax(pad_l, pad_extend * centerness);
6583
        pad_r = ImMax(pad_r, pad_extend * centerness);
6584
    }
6585
6586
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6587
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6588
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6589
    {
6590
        ImVec2 marker_pos;
6591
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6592
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6593
        if (marker_pos.x > layout_r.Min.x)
6594
        {
6595
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6596
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6597
        }
6598
    }
6599
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6600
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6601
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6602
}
6603
6604
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6605
{
6606
    window->ParentWindow = parent_window;
6607
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6608
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6609
    {
6610
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6611
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6612
            window->RootWindow = parent_window->RootWindow;
6613
    }
6614
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6615
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6616
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6617
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6618
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6619
    {
6620
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6621
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6622
    }
6623
}
6624
6625
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6626
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6627
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6628
// - Window             // FindBlockingModal() returns Modal1
6629
//   - Window           //                  .. returns Modal1
6630
//   - Modal1           //                  .. returns Modal2
6631
//      - Window        //                  .. returns Modal2
6632
//          - Window    //                  .. returns Modal2
6633
//          - Modal2    //                  .. returns Modal2
6634
static ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6635
{
6636
    ImGuiContext& g = *GImGui;
6637
    if (g.OpenPopupStack.Size <= 0)
6638
        return NULL;
6639
6640
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6641
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
6642
    {
6643
        ImGuiWindow* popup_window = g.OpenPopupStack.Data[i].Window;
6644
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6645
            continue;
6646
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6647
            continue;
6648
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window is rendered over last modal, no render order change needed.
6649
            break;
6650
        for (ImGuiWindow* parent = popup_window->ParentWindowInBeginStack->RootWindow; parent != NULL; parent = parent->ParentWindowInBeginStack->RootWindow)
6651
            if (IsWindowWithinBeginStackOf(window, parent))
6652
                return popup_window;                                // Place window above its begin stack parent.
6653
    }
6654
    return NULL;
6655
}
6656
6657
// Push a new Dear ImGui window to add widgets to.
6658
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6659
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6660
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6661
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6662
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6663
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6664
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6665
{
6666
    ImGuiContext& g = *GImGui;
6667
    const ImGuiStyle& style = g.Style;
6668
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6669
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6670
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6671
6672
    // Find or create
6673
    ImGuiWindow* window = FindWindowByName(name);
6674
    const bool window_just_created = (window == NULL);
6675
    if (window_just_created)
6676
        window = CreateNewWindow(name, flags);
6677
6678
    // Automatically disable manual moving/resizing when NoInputs is set
6679
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6680
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6681
6682
    if (flags & ImGuiWindowFlags_NavFlattened)
6683
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6684
6685
    const int current_frame = g.FrameCount;
6686
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6687
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6688
6689
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6690
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6691
    if (flags & ImGuiWindowFlags_Popup)
6692
    {
6693
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6694
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6695
        window_just_activated_by_user |= (window != popup_ref.Window);
6696
    }
6697
6698
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6699
    const bool window_was_appearing = window->Appearing;
6700
    if (first_begin_of_the_frame)
6701
    {
6702
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6703
        window->Appearing = window_just_activated_by_user;
6704
        if (window->Appearing)
6705
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6706
        window->FlagsPreviousFrame = window->Flags;
6707
        window->Flags = (ImGuiWindowFlags)flags;
6708
        window->LastFrameActive = current_frame;
6709
        window->LastTimeActive = (float)g.Time;
6710
        window->BeginOrderWithinParent = 0;
6711
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6712
    }
6713
    else
6714
    {
6715
        flags = window->Flags;
6716
    }
6717
6718
    // Docking
6719
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6720
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6721
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6722
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6723
    if (first_begin_of_the_frame)
6724
    {
6725
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6726
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6727
        bool dock_node_was_visible = window->DockNodeIsVisible;
6728
        bool dock_tab_was_visible = window->DockTabIsVisible;
6729
        if (has_dock_node || new_auto_dock_node)
6730
        {
6731
            BeginDocked(window, p_open);
6732
            flags = window->Flags;
6733
            if (window->DockIsActive)
6734
            {
6735
                IM_ASSERT(window->DockNode != NULL);
6736
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6737
            }
6738
6739
            // Amend the Appearing flag
6740
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6741
            {
6742
                window->Appearing = true;
6743
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6744
            }
6745
        }
6746
        else
6747
        {
6748
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6749
        }
6750
    }
6751
6752
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6753
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6754
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6755
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6756
6757
    // We allow window memory to be compacted so recreate the base stack when needed.
6758
    if (window->IDStack.Size == 0)
6759
        window->IDStack.push_back(window->ID);
6760
6761
    // Add to stack
6762
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6763
    g.CurrentWindow = window;
6764
    ImGuiWindowStackData window_stack_data;
6765
    window_stack_data.Window = window;
6766
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6767
    window_stack_data.StackSizesOnBegin.SetToCurrentState();
6768
    g.CurrentWindowStack.push_back(window_stack_data);
6769
    if (flags & ImGuiWindowFlags_ChildMenu)
6770
        g.BeginMenuCount++;
6771
6772
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6773
    if (first_begin_of_the_frame)
6774
    {
6775
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6776
        window->ParentWindowInBeginStack = parent_window_in_stack;
6777
    }
6778
6779
    // Add to focus scope stack
6780
    PushFocusScope(window->ID);
6781
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6782
    g.CurrentWindow = NULL;
6783
6784
    // Add to popup stack
6785
    if (flags & ImGuiWindowFlags_Popup)
6786
    {
6787
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6788
        popup_ref.Window = window;
6789
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6790
        g.BeginPopupStack.push_back(popup_ref);
6791
        window->PopupId = popup_ref.PopupId;
6792
    }
6793
6794
    // Process SetNextWindow***() calls
6795
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6796
    bool window_pos_set_by_api = false;
6797
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6798
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6799
    {
6800
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6801
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6802
        {
6803
            // May be processed on the next frame if this is our first frame and we are measuring size
6804
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6805
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6806
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6807
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6808
        }
6809
        else
6810
        {
6811
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6812
        }
6813
    }
6814
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6815
    {
6816
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6817
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6818
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6819
    }
6820
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6821
    {
6822
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6823
        {
6824
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6825
            window->ScrollTargetCenterRatio.x = 0.0f;
6826
        }
6827
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6828
        {
6829
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6830
            window->ScrollTargetCenterRatio.y = 0.0f;
6831
        }
6832
    }
6833
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6834
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6835
    else if (first_begin_of_the_frame)
6836
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6837
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6838
        window->WindowClass = g.NextWindowData.WindowClass;
6839
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6840
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6841
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6842
        FocusWindow(window);
6843
    if (window->Appearing)
6844
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6845
6846
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6847
    if (first_begin_of_the_frame)
6848
    {
6849
        // Initialize
6850
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6851
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6852
        window->Active = true;
6853
        window->HasCloseButton = (p_open != NULL);
6854
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6855
        window->IDStack.resize(1);
6856
        window->DrawList->_ResetForNewFrame();
6857
        window->DC.CurrentTableIdx = -1;
6858
        if (flags & ImGuiWindowFlags_DockNodeHost)
6859
        {
6860
            window->DrawList->ChannelsSplit(2);
6861
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6862
        }
6863
6864
        // Restore buffer capacity when woken from a compacted state, to avoid
6865
        if (window->MemoryCompacted)
6866
            GcAwakeTransientWindowBuffers(window);
6867
6868
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6869
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6870
        bool window_title_visible_elsewhere = false;
6871
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6872
            window_title_visible_elsewhere = true;
6873
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6874
            window_title_visible_elsewhere = true;
6875
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6876
        {
6877
            size_t buf_len = (size_t)window->NameBufLen;
6878
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6879
            window->NameBufLen = (int)buf_len;
6880
        }
6881
6882
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6883
6884
        // Update contents size from last frame for auto-fitting (or use explicit size)
6885
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6886
6887
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6888
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6889
        // it has a single usage before this code block and may be set below before it is finally checked.
6890
        if (window->HiddenFramesCanSkipItems > 0)
6891
            window->HiddenFramesCanSkipItems--;
6892
        if (window->HiddenFramesCannotSkipItems > 0)
6893
            window->HiddenFramesCannotSkipItems--;
6894
        if (window->HiddenFramesForRenderOnly > 0)
6895
            window->HiddenFramesForRenderOnly--;
6896
6897
        // Hide new windows for one frame until they calculate their size
6898
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6899
            window->HiddenFramesCannotSkipItems = 1;
6900
6901
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6902
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6903
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6904
        {
6905
            window->HiddenFramesCannotSkipItems = 1;
6906
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6907
            {
6908
                if (!window_size_x_set_by_api)
6909
                    window->Size.x = window->SizeFull.x = 0.f;
6910
                if (!window_size_y_set_by_api)
6911
                    window->Size.y = window->SizeFull.y = 0.f;
6912
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6913
            }
6914
        }
6915
6916
        // SELECT VIEWPORT
6917
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6918
6919
        WindowSelectViewport(window);
6920
        SetCurrentViewport(window, window->Viewport);
6921
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6922
        SetCurrentWindow(window);
6923
        flags = window->Flags;
6924
6925
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
6926
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
6927
6928
        if (flags & ImGuiWindowFlags_ChildWindow)
6929
            window->WindowBorderSize = style.ChildBorderSize;
6930
        else
6931
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
6932
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
6933
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
6934
        else
6935
            window->WindowPadding = style.WindowPadding;
6936
6937
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
6938
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
6939
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
6940
6941
        bool use_current_size_for_scrollbar_x = window_just_created;
6942
        bool use_current_size_for_scrollbar_y = window_just_created;
6943
6944
        // Collapse window by double-clicking on title bar
6945
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
6946
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
6947
        {
6948
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
6949
            ImRect title_bar_rect = window->TitleBarRect();
6950
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
6951
                window->WantCollapseToggle = true;
6952
            if (window->WantCollapseToggle)
6953
            {
6954
                window->Collapsed = !window->Collapsed;
6955
                if (!window->Collapsed)
6956
                    use_current_size_for_scrollbar_y = true;
6957
                MarkIniSettingsDirty(window);
6958
            }
6959
        }
6960
        else
6961
        {
6962
            window->Collapsed = false;
6963
        }
6964
        window->WantCollapseToggle = false;
6965
6966
        // SIZE
6967
6968
        // Calculate auto-fit size, handle automatic resize
6969
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
6970
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
6971
        {
6972
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
6973
            if (!window_size_x_set_by_api)
6974
            {
6975
                window->SizeFull.x = size_auto_fit.x;
6976
                use_current_size_for_scrollbar_x = true;
6977
            }
6978
            if (!window_size_y_set_by_api)
6979
            {
6980
                window->SizeFull.y = size_auto_fit.y;
6981
                use_current_size_for_scrollbar_y = true;
6982
            }
6983
        }
6984
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6985
        {
6986
            // Auto-fit may only grow window during the first few frames
6987
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
6988
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
6989
            {
6990
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
6991
                use_current_size_for_scrollbar_x = true;
6992
            }
6993
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
6994
            {
6995
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
6996
                use_current_size_for_scrollbar_y = true;
6997
            }
6998
            if (!window->Collapsed)
6999
                MarkIniSettingsDirty(window);
7000
        }
7001
7002
        // Apply minimum/maximum window size constraints and final size
7003
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7004
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7005
7006
        // Decoration size
7007
        const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
7008
7009
        // POSITION
7010
7011
        // Popup latch its initial position, will position itself when it appears next frame
7012
        if (window_just_activated_by_user)
7013
        {
7014
            window->AutoPosLastDirection = ImGuiDir_None;
7015
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7016
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7017
        }
7018
7019
        // Position child window
7020
        if (flags & ImGuiWindowFlags_ChildWindow)
7021
        {
7022
            IM_ASSERT(parent_window && parent_window->Active);
7023
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7024
            parent_window->DC.ChildWindows.push_back(window);
7025
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7026
                window->Pos = parent_window->DC.CursorPos;
7027
        }
7028
7029
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7030
        if (window_pos_with_pivot)
7031
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7032
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7033
            window->Pos = FindBestWindowPosForPopup(window);
7034
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7035
            window->Pos = FindBestWindowPosForPopup(window);
7036
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7037
            window->Pos = FindBestWindowPosForPopup(window);
7038
7039
        // Late create viewport if we don't fit within our current host viewport.
7040
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_Minimized))
7041
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7042
            {
7043
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7044
                //ImGuiViewport* old_viewport = window->Viewport;
7045
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7046
7047
                // FIXME-DPI
7048
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7049
                SetCurrentViewport(window, window->Viewport);
7050
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7051
                SetCurrentWindow(window);
7052
            }
7053
7054
        if (window->ViewportOwned)
7055
            WindowSyncOwnedViewport(window, parent_window_in_stack);
7056
7057
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7058
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7059
        ImRect viewport_rect(window->Viewport->GetMainRect());
7060
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7061
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7062
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7063
7064
        // Clamp position/size so window stays visible within its viewport or monitor
7065
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7066
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
7067
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7068
        {
7069
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7070
            {
7071
                ClampWindowPos(window, visibility_rect);
7072
            }
7073
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7074
            {
7075
                // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7076
                const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7077
                visibility_rect.Min = monitor->WorkPos + visibility_padding;
7078
                visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
7079
                ClampWindowPos(window, visibility_rect);
7080
            }
7081
        }
7082
        window->Pos = ImFloor(window->Pos);
7083
7084
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7085
        // Large values tend to lead to variety of artifacts and are not recommended.
7086
        if (window->ViewportOwned || window->DockIsActive)
7087
            window->WindowRounding = 0.0f;
7088
        else
7089
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7090
7091
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7092
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7093
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7094
7095
        // Apply window focus (new and reactivated windows are moved to front)
7096
        bool want_focus = false;
7097
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7098
        {
7099
            if (flags & ImGuiWindowFlags_Popup)
7100
                want_focus = true;
7101
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7102
                want_focus = true;
7103
7104
            ImGuiWindow* modal = GetTopMostPopupModal();
7105
            if (modal != NULL && !IsWindowWithinBeginStackOf(window, modal))
7106
            {
7107
                // Avoid focusing a window that is created outside of active modal. This will prevent active modal from being closed.
7108
                // Since window is not focused it would reappear at the same display position like the last time it was visible.
7109
                // In case of completely new windows it would go to the top (over current modal), but input to such window would still be blocked by modal.
7110
                // Position window behind a modal that is not a begin-parent of this window.
7111
                want_focus = false;
7112
                if (window == window->RootWindow)
7113
                {
7114
                    ImGuiWindow* blocking_modal = FindBlockingModal(window);
7115
                    IM_ASSERT(blocking_modal != NULL);
7116
                    BringWindowToDisplayBehind(window, blocking_modal);
7117
                }
7118
            }
7119
        }
7120
7121
        // [Test Engine] Register whole window in the item system
7122
#ifdef IMGUI_ENABLE_TEST_ENGINE
7123
        if (g.TestEngineHookItems)
7124
        {
7125
            IM_ASSERT(window->IDStack.Size == 1);
7126
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7127
            IMGUI_TEST_ENGINE_ITEM_ADD(window->Rect(), window->ID);
7128
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7129
            window->IDStack.Size = 1;
7130
        }
7131
#endif
7132
7133
        // Decide if we are going to handle borders and resize grips
7134
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7135
7136
        // Handle manual resize: Resize Grips, Borders, Gamepad
7137
        int border_held = -1;
7138
        ImU32 resize_grip_col[4] = {};
7139
        const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7140
        const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7141
        if (handle_borders_and_resize_grips && !window->Collapsed)
7142
            if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7143
                use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
7144
        window->ResizeBorderHeld = (signed char)border_held;
7145
7146
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7147
        if (window->ViewportOwned)
7148
        {
7149
            if (!window->Viewport->PlatformRequestMove)
7150
                window->Viewport->Pos = window->Pos;
7151
            if (!window->Viewport->PlatformRequestResize)
7152
                window->Viewport->Size = window->Size;
7153
            window->Viewport->UpdateWorkRect();
7154
            viewport_rect = window->Viewport->GetMainRect();
7155
        }
7156
7157
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7158
        window->ViewportPos = window->Viewport->Pos;
7159
7160
        // SCROLLBAR VISIBILITY
7161
7162
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7163
        if (!window->Collapsed)
7164
        {
7165
            // When reading the current size we need to read it after size constraints have been applied.
7166
            // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.
7167
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);
7168
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;
7169
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7170
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7171
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7172
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7173
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7174
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7175
            if (window->ScrollbarX && !window->ScrollbarY)
7176
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
7177
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7178
        }
7179
7180
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7181
        // Update various regions. Variables they depend on should be set above in this function.
7182
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7183
7184
        // Outer rectangle
7185
        // Not affected by window border size. Used by:
7186
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7187
        // - Begin() initial clipping rect for drawing window background and borders.
7188
        // - Begin() clipping whole child
7189
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7190
        const ImRect outer_rect = window->Rect();
7191
        const ImRect title_bar_rect = window->TitleBarRect();
7192
        window->OuterRectClipped = outer_rect;
7193
        if (window->DockIsActive)
7194
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
7195
        window->OuterRectClipped.ClipWith(host_rect);
7196
7197
        // Inner rectangle
7198
        // Not affected by window border size. Used by:
7199
        // - InnerClipRect
7200
        // - ScrollToRectEx()
7201
        // - NavUpdatePageUpPageDown()
7202
        // - Scrollbar()
7203
        window->InnerRect.Min.x = window->Pos.x;
7204
        window->InnerRect.Min.y = window->Pos.y + decoration_up_height;
7205
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;
7206
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;
7207
7208
        // Inner clipping rectangle.
7209
        // Will extend a little bit outside the normal work region.
7210
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7211
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7212
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7213
        // Affected by window/frame border size. Used by:
7214
        // - Begin() initial clip rect
7215
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7216
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7217
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7218
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7219
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7220
        window->InnerClipRect.ClipWithFull(host_rect);
7221
7222
        // Default item width. Make it proportional to window size if window manually resizes
7223
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7224
            window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
7225
        else
7226
            window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
7227
7228
        // SCROLLING
7229
7230
        // Lock down maximum scrolling
7231
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7232
        // for right/bottom aligned items without creating a scrollbar.
7233
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7234
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7235
7236
        // Apply scrolling
7237
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7238
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7239
7240
        // DRAWING
7241
7242
        // Setup draw list and outer clipping rectangle
7243
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7244
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7245
        PushClipRect(host_rect.Min, host_rect.Max, false);
7246
7247
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7248
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7249
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7250
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7251
        if (is_undocked_or_docked_visible)
7252
        {
7253
            bool render_decorations_in_parent = false;
7254
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7255
            {
7256
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7257
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7258
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7259
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7260
                bool parent_is_empty = parent_window->DrawList->VtxBuffer.Size > 0;
7261
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_is_empty && !previous_child_overlapping)
7262
                    render_decorations_in_parent = true;
7263
            }
7264
            if (render_decorations_in_parent)
7265
                window->DrawList = parent_window->DrawList;
7266
7267
            // Handle title bar, scrollbar, resize grips and resize borders
7268
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7269
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7270
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7271
7272
            if (render_decorations_in_parent)
7273
                window->DrawList = &window->DrawListInst;
7274
        }
7275
7276
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7277
7278
        // Work rectangle.
7279
        // Affected by window padding and border size. Used by:
7280
        // - Columns() for right-most edge
7281
        // - TreeNode(), CollapsingHeader() for right-most edge
7282
        // - BeginTabBar() for right-most edge
7283
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7284
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7285
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
7286
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
7287
        window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7288
        window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7289
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7290
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7291
        window->ParentWorkRect = window->WorkRect;
7292
7293
        // [LEGACY] Content Region
7294
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7295
        // Used by:
7296
        // - Mouse wheel scrolling + many other things
7297
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
7298
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
7299
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
7300
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
7301
7302
        // Setup drawing context
7303
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7304
        window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
7305
        window->DC.GroupOffset.x = 0.0f;
7306
        window->DC.ColumnsOffset.x = 0.0f;
7307
7308
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7309
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7310
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DC.ColumnsOffset.x;
7311
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + decoration_up_height;
7312
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7313
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7314
        window->DC.CursorPos = window->DC.CursorStartPos;
7315
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7316
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7317
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7318
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7319
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7320
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7321
7322
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7323
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7324
        window->DC.NavLayersActiveMaskNext = 0x00;
7325
        window->DC.NavHideHighlightOneFrame = false;
7326
        window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
7327
7328
        window->DC.MenuBarAppending = false;
7329
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7330
        window->DC.TreeDepth = 0;
7331
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7332
        window->DC.ChildWindows.resize(0);
7333
        window->DC.StateStorage = &window->StateStorage;
7334
        window->DC.CurrentColumns = NULL;
7335
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7336
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7337
7338
        window->DC.ItemWidth = window->ItemWidthDefault;
7339
        window->DC.TextWrapPos = -1.0f; // disabled
7340
        window->DC.ItemWidthStack.resize(0);
7341
        window->DC.TextWrapPosStack.resize(0);
7342
7343
        if (window->AutoFitFramesX > 0)
7344
            window->AutoFitFramesX--;
7345
        if (window->AutoFitFramesY > 0)
7346
            window->AutoFitFramesY--;
7347
7348
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7349
        if (want_focus)
7350
        {
7351
            FocusWindow(window);
7352
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7353
        }
7354
7355
        // Close requested by platform window
7356
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7357
        {
7358
            if (!window->DockIsActive || window->DockTabIsVisible)
7359
            {
7360
                window->Viewport->PlatformRequestClose = false;
7361
                g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue.
7362
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' PlatformRequestClose\n", window->Name);
7363
                *p_open = false;
7364
            }
7365
        }
7366
7367
        // Title bar
7368
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7369
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7370
7371
        // Clear hit test shape every frame
7372
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7373
7374
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7375
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7376
        // Maybe we can support CTRL+C on every element?
7377
        /*
7378
        //if (g.NavWindow == window && g.ActiveId == 0)
7379
        if (g.ActiveId == window->MoveId)
7380
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7381
                LogToClipboard();
7382
        */
7383
7384
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7385
        {
7386
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7387
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7388
            if ((g.MovingWindow == window) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift))
7389
                if ((window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7390
                    BeginDockableDragDropSource(window);
7391
7392
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7393
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7394
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7395
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7396
                        BeginDockableDragDropTarget(window);
7397
        }
7398
7399
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7400
        // This is useful to allow creating context menus on title bar only, etc.
7401
        if (window->DockIsActive)
7402
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7403
        else
7404
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7405
7406
        // [DEBUG]
7407
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7408
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7409
            DebugLocateItemResolveWithLastItem();
7410
#endif
7411
7412
        // [Test Engine] Register title bar / tab
7413
#ifdef IMGUI_ENABLE_TEST_ENGINE
7414
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7415
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.Rect, g.LastItemData.ID);
7416
#endif
7417
    }
7418
    else
7419
    {
7420
        // Append
7421
        SetCurrentViewport(window, window->Viewport);
7422
        SetCurrentWindow(window);
7423
    }
7424
7425
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7426
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7427
7428
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7429
    window->WriteAccessed = false;
7430
    window->BeginCount++;
7431
    g.NextWindowData.ClearFlags();
7432
7433
    // Update visibility
7434
    if (first_begin_of_the_frame)
7435
    {
7436
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7437
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7438
        // This is analogous to regular windows being hidden from one frame.
7439
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7440
        if (window->DockIsActive && !window->DockTabIsVisible)
7441
        {
7442
            if (window->LastFrameJustFocused == g.FrameCount)
7443
                window->HiddenFramesCannotSkipItems = 1;
7444
            else
7445
                window->HiddenFramesCanSkipItems = 1;
7446
        }
7447
7448
        if (flags & ImGuiWindowFlags_ChildWindow)
7449
        {
7450
            // Child window can be out of sight and have "negative" clip windows.
7451
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7452
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
7453
            if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
7454
            {
7455
                const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7456
                if (!g.LogEnabled && !nav_request)
7457
                    if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7458
                        window->HiddenFramesCanSkipItems = 1;
7459
            }
7460
7461
            // Hide along with parent or if parent is collapsed
7462
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7463
                window->HiddenFramesCanSkipItems = 1;
7464
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7465
                window->HiddenFramesCannotSkipItems = 1;
7466
        }
7467
7468
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7469
        if (style.Alpha <= 0.0f)
7470
            window->HiddenFramesCanSkipItems = 1;
7471
7472
        // Update the Hidden flag
7473
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7474
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7475
7476
        // Disable inputs for requested number of frames
7477
        if (window->DisableInputsFrames > 0)
7478
        {
7479
            window->DisableInputsFrames--;
7480
            window->Flags |= ImGuiWindowFlags_NoInputs;
7481
        }
7482
7483
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7484
        bool skip_items = false;
7485
        if (window->Collapsed || !window->Active || hidden_regular)
7486
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7487
                skip_items = true;
7488
        window->SkipItems = skip_items;
7489
7490
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7491
        if (window->SkipItems)
7492
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7493
7494
        // Sanity check: there are two spots which can set Appearing = true
7495
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7496
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7497
        if (window->SkipItems && !window->Appearing)
7498
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7499
    }
7500
7501
    return !window->SkipItems;
7502
}
7503
7504
void ImGui::End()
7505
{
7506
    ImGuiContext& g = *GImGui;
7507
    ImGuiWindow* window = g.CurrentWindow;
7508
7509
    // Error checking: verify that user hasn't called End() too many times!
7510
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7511
    {
7512
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7513
        return;
7514
    }
7515
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7516
7517
    // Error checking: verify that user doesn't directly call End() on a child window.
7518
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7519
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7520
7521
    // Close anything that is open
7522
    if (window->DC.CurrentColumns)
7523
        EndColumns();
7524
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7525
        PopClipRect();
7526
    PopFocusScope();
7527
7528
    // Stop logging
7529
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7530
        LogFinish();
7531
7532
    if (window->DC.IsSetPos)
7533
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7534
7535
    // Docking: report contents sizes to parent to allow for auto-resize
7536
    if (window->DockNode && window->DockTabIsVisible)
7537
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7538
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7539
7540
    // Pop from window stack
7541
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7542
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7543
        g.BeginMenuCount--;
7544
    if (window->Flags & ImGuiWindowFlags_Popup)
7545
        g.BeginPopupStack.pop_back();
7546
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithCurrentState();
7547
    g.CurrentWindowStack.pop_back();
7548
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7549
    if (g.CurrentWindow)
7550
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7551
}
7552
7553
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7554
{
7555
    ImGuiContext& g = *GImGui;
7556
    IM_ASSERT(window == window->RootWindow);
7557
7558
    const int cur_order = window->FocusOrder;
7559
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7560
    if (g.WindowsFocusOrder.back() == window)
7561
        return;
7562
7563
    const int new_order = g.WindowsFocusOrder.Size - 1;
7564
    for (int n = cur_order; n < new_order; n++)
7565
    {
7566
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7567
        g.WindowsFocusOrder[n]->FocusOrder--;
7568
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7569
    }
7570
    g.WindowsFocusOrder[new_order] = window;
7571
    window->FocusOrder = (short)new_order;
7572
}
7573
7574
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7575
{
7576
    ImGuiContext& g = *GImGui;
7577
    ImGuiWindow* current_front_window = g.Windows.back();
7578
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7579
        return;
7580
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7581
        if (g.Windows[i] == window)
7582
        {
7583
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7584
            g.Windows[g.Windows.Size - 1] = window;
7585
            break;
7586
        }
7587
}
7588
7589
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7590
{
7591
    ImGuiContext& g = *GImGui;
7592
    if (g.Windows[0] == window)
7593
        return;
7594
    for (int i = 0; i < g.Windows.Size; i++)
7595
        if (g.Windows[i] == window)
7596
        {
7597
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7598
            g.Windows[0] = window;
7599
            break;
7600
        }
7601
}
7602
7603
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7604
{
7605
    IM_ASSERT(window != NULL && behind_window != NULL);
7606
    ImGuiContext& g = *GImGui;
7607
    window = window->RootWindow;
7608
    behind_window = behind_window->RootWindow;
7609
    int pos_wnd = FindWindowDisplayIndex(window);
7610
    int pos_beh = FindWindowDisplayIndex(behind_window);
7611
    if (pos_wnd < pos_beh)
7612
    {
7613
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7614
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7615
        g.Windows[pos_beh - 1] = window;
7616
    }
7617
    else
7618
    {
7619
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7620
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7621
        g.Windows[pos_beh] = window;
7622
    }
7623
}
7624
7625
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7626
{
7627
    ImGuiContext& g = *GImGui;
7628
    return g.Windows.index_from_ptr(g.Windows.find(window));
7629
}
7630
7631
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7632
void ImGui::FocusWindow(ImGuiWindow* window)
7633
{
7634
    ImGuiContext& g = *GImGui;
7635
7636
    if (g.NavWindow != window)
7637
    {
7638
        SetNavWindow(window);
7639
        if (window && g.NavDisableMouseHover)
7640
            g.NavMousePosDirty = true;
7641
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7642
        g.NavLayer = ImGuiNavLayer_Main;
7643
        g.NavFocusScopeId = window ? window->NavRootFocusScopeId : 0;
7644
        g.NavIdIsAlive = false;
7645
7646
        // Close popups if any
7647
        ClosePopupsOverWindow(window, false);
7648
    }
7649
7650
    // Move the root window to the top of the pile
7651
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7652
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7653
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7654
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7655
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7656
7657
    // Steal active widgets. Some of the cases it triggers includes:
7658
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7659
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7660
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7661
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7662
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7663
            ClearActiveID();
7664
7665
    // Passing NULL allow to disable keyboard focus
7666
    if (!window)
7667
        return;
7668
    window->LastFrameJustFocused = g.FrameCount;
7669
7670
    // Select in dock node
7671
    if (dock_node && dock_node->TabBar)
7672
        dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7673
7674
    // Bring to front
7675
    BringWindowToFocusFront(focus_front_window);
7676
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7677
        BringWindowToDisplayFront(display_front_window);
7678
}
7679
7680
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
7681
{
7682
    ImGuiContext& g = *GImGui;
7683
    int start_idx = g.WindowsFocusOrder.Size - 1;
7684
    if (under_this_window != NULL)
7685
    {
7686
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7687
        int offset = -1;
7688
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7689
        {
7690
            under_this_window = under_this_window->ParentWindow;
7691
            offset = 0;
7692
        }
7693
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7694
    }
7695
    for (int i = start_idx; i >= 0; i--)
7696
    {
7697
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7698
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7699
        IM_ASSERT(window == window->RootWindow);
7700
        if (window != ignore_window && window->WasActive)
7701
            if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7702
            {
7703
                // FIXME-DOCK: This is failing (lagging by one frame) for docked windows.
7704
                // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7705
                // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7706
                // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7707
                ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
7708
                FocusWindow(focus_window);
7709
                return;
7710
            }
7711
    }
7712
    FocusWindow(NULL);
7713
}
7714
7715
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7716
void ImGui::SetCurrentFont(ImFont* font)
7717
{
7718
    ImGuiContext& g = *GImGui;
7719
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7720
    IM_ASSERT(font->Scale > 0.0f);
7721
    g.Font = font;
7722
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7723
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7724
7725
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7726
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7727
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7728
    g.DrawListSharedData.Font = g.Font;
7729
    g.DrawListSharedData.FontSize = g.FontSize;
7730
}
7731
7732
void ImGui::PushFont(ImFont* font)
7733
{
7734
    ImGuiContext& g = *GImGui;
7735
    if (!font)
7736
        font = GetDefaultFont();
7737
    SetCurrentFont(font);
7738
    g.FontStack.push_back(font);
7739
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7740
}
7741
7742
void  ImGui::PopFont()
7743
{
7744
    ImGuiContext& g = *GImGui;
7745
    g.CurrentWindow->DrawList->PopTextureID();
7746
    g.FontStack.pop_back();
7747
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7748
}
7749
7750
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7751
{
7752
    ImGuiContext& g = *GImGui;
7753
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7754
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7755
    if (enabled)
7756
        item_flags |= option;
7757
    else
7758
        item_flags &= ~option;
7759
    g.CurrentItemFlags = item_flags;
7760
    g.ItemFlagsStack.push_back(item_flags);
7761
}
7762
7763
void ImGui::PopItemFlag()
7764
{
7765
    ImGuiContext& g = *GImGui;
7766
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7767
    g.ItemFlagsStack.pop_back();
7768
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7769
}
7770
7771
// BeginDisabled()/EndDisabled()
7772
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7773
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7774
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7775
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7776
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7777
void ImGui::BeginDisabled(bool disabled)
7778
{
7779
    ImGuiContext& g = *GImGui;
7780
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7781
    if (!was_disabled && disabled)
7782
    {
7783
        g.DisabledAlphaBackup = g.Style.Alpha;
7784
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7785
    }
7786
    if (was_disabled || disabled)
7787
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7788
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7789
    g.DisabledStackSize++;
7790
}
7791
7792
void ImGui::EndDisabled()
7793
{
7794
    ImGuiContext& g = *GImGui;
7795
    IM_ASSERT(g.DisabledStackSize > 0);
7796
    g.DisabledStackSize--;
7797
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7798
    //PopItemFlag();
7799
    g.ItemFlagsStack.pop_back();
7800
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7801
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7802
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7803
}
7804
7805
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
7806
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
7807
{
7808
    PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
7809
}
7810
7811
void ImGui::PopAllowKeyboardFocus()
7812
{
7813
    PopItemFlag();
7814
}
7815
7816
void ImGui::PushButtonRepeat(bool repeat)
7817
{
7818
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7819
}
7820
7821
void ImGui::PopButtonRepeat()
7822
{
7823
    PopItemFlag();
7824
}
7825
7826
void ImGui::PushTextWrapPos(float wrap_pos_x)
7827
{
7828
    ImGuiWindow* window = GetCurrentWindow();
7829
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7830
    window->DC.TextWrapPos = wrap_pos_x;
7831
}
7832
7833
void ImGui::PopTextWrapPos()
7834
{
7835
    ImGuiWindow* window = GetCurrentWindow();
7836
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7837
    window->DC.TextWrapPosStack.pop_back();
7838
}
7839
7840
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7841
{
7842
    ImGuiWindow* last_window = NULL;
7843
    while (last_window != window)
7844
    {
7845
        last_window = window;
7846
        window = window->RootWindow;
7847
        if (popup_hierarchy)
7848
            window = window->RootWindowPopupTree;
7849
		if (dock_hierarchy)
7850
			window = window->RootWindowDockTree;
7851
	}
7852
    return window;
7853
}
7854
7855
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7856
{
7857
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7858
    if (window_root == potential_parent)
7859
        return true;
7860
    while (window != NULL)
7861
    {
7862
        if (window == potential_parent)
7863
            return true;
7864
        if (window == window_root) // end of chain
7865
            return false;
7866
        window = window->ParentWindow;
7867
    }
7868
    return false;
7869
}
7870
7871
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7872
{
7873
    if (window->RootWindow == potential_parent)
7874
        return true;
7875
    while (window != NULL)
7876
    {
7877
        if (window == potential_parent)
7878
            return true;
7879
        window = window->ParentWindowInBeginStack;
7880
    }
7881
    return false;
7882
}
7883
7884
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7885
{
7886
    ImGuiContext& g = *GImGui;
7887
7888
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
7889
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
7890
    if (display_layer_delta != 0)
7891
        return display_layer_delta > 0;
7892
7893
    for (int i = g.Windows.Size - 1; i >= 0; i--)
7894
    {
7895
        ImGuiWindow* candidate_window = g.Windows[i];
7896
        if (candidate_window == potential_above)
7897
            return true;
7898
        if (candidate_window == potential_below)
7899
            return false;
7900
    }
7901
    return false;
7902
}
7903
7904
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
7905
{
7906
    IM_ASSERT((flags & (ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled)) == 0);   // Flags not supported by this function
7907
    ImGuiContext& g = *GImGui;
7908
    ImGuiWindow* ref_window = g.HoveredWindow;
7909
    ImGuiWindow* cur_window = g.CurrentWindow;
7910
    if (ref_window == NULL)
7911
        return false;
7912
7913
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
7914
    {
7915
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
7916
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
7917
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
7918
        if (flags & ImGuiHoveredFlags_RootWindow)
7919
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7920
7921
        bool result;
7922
        if (flags & ImGuiHoveredFlags_ChildWindows)
7923
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7924
        else
7925
            result = (ref_window == cur_window);
7926
        if (!result)
7927
            return false;
7928
    }
7929
7930
    if (!IsWindowContentHoverable(ref_window, flags))
7931
        return false;
7932
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
7933
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
7934
            return false;
7935
    return true;
7936
}
7937
7938
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
7939
{
7940
    ImGuiContext& g = *GImGui;
7941
    ImGuiWindow* ref_window = g.NavWindow;
7942
    ImGuiWindow* cur_window = g.CurrentWindow;
7943
7944
    if (ref_window == NULL)
7945
        return false;
7946
    if (flags & ImGuiFocusedFlags_AnyWindow)
7947
        return true;
7948
7949
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
7950
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
7951
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
7952
    if (flags & ImGuiHoveredFlags_RootWindow)
7953
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7954
7955
    if (flags & ImGuiHoveredFlags_ChildWindows)
7956
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7957
    else
7958
        return (ref_window == cur_window);
7959
}
7960
7961
ImGuiID ImGui::GetWindowDockID()
7962
{
7963
    ImGuiContext& g = *GImGui;
7964
    return g.CurrentWindow->DockId;
7965
}
7966
7967
bool ImGui::IsWindowDocked()
7968
{
7969
    ImGuiContext& g = *GImGui;
7970
    return g.CurrentWindow->DockIsActive;
7971
}
7972
7973
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
7974
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
7975
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
7976
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
7977
{
7978
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
7979
}
7980
7981
float ImGui::GetWindowWidth()
7982
{
7983
    ImGuiWindow* window = GImGui->CurrentWindow;
7984
    return window->Size.x;
7985
}
7986
7987
float ImGui::GetWindowHeight()
7988
{
7989
    ImGuiWindow* window = GImGui->CurrentWindow;
7990
    return window->Size.y;
7991
}
7992
7993
ImVec2 ImGui::GetWindowPos()
7994
{
7995
    ImGuiContext& g = *GImGui;
7996
    ImGuiWindow* window = g.CurrentWindow;
7997
    return window->Pos;
7998
}
7999
8000
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8001
{
8002
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8003
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8004
        return;
8005
8006
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8007
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8008
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8009
8010
    // Set
8011
    const ImVec2 old_pos = window->Pos;
8012
    window->Pos = ImFloor(pos);
8013
    ImVec2 offset = window->Pos - old_pos;
8014
    if (offset.x == 0.0f && offset.y == 0.0f)
8015
        return;
8016
    MarkIniSettingsDirty(window);
8017
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8018
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8019
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8020
    window->DC.IdealMaxPos += offset;
8021
    window->DC.CursorStartPos += offset;
8022
}
8023
8024
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8025
{
8026
    ImGuiWindow* window = GetCurrentWindowRead();
8027
    SetWindowPos(window, pos, cond);
8028
}
8029
8030
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8031
{
8032
    if (ImGuiWindow* window = FindWindowByName(name))
8033
        SetWindowPos(window, pos, cond);
8034
}
8035
8036
ImVec2 ImGui::GetWindowSize()
8037
{
8038
    ImGuiWindow* window = GetCurrentWindowRead();
8039
    return window->Size;
8040
}
8041
8042
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8043
{
8044
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8045
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8046
        return;
8047
8048
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8049
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8050
8051
    // Set
8052
    ImVec2 old_size = window->SizeFull;
8053
    window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8054
    window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8055
    if (size.x <= 0.0f)
8056
        window->AutoFitOnlyGrows = false;
8057
    else
8058
        window->SizeFull.x = IM_FLOOR(size.x);
8059
    if (size.y <= 0.0f)
8060
        window->AutoFitOnlyGrows = false;
8061
    else
8062
        window->SizeFull.y = IM_FLOOR(size.y);
8063
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8064
        MarkIniSettingsDirty(window);
8065
}
8066
8067
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8068
{
8069
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8070
}
8071
8072
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8073
{
8074
    if (ImGuiWindow* window = FindWindowByName(name))
8075
        SetWindowSize(window, size, cond);
8076
}
8077
8078
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8079
{
8080
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8081
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8082
        return;
8083
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8084
8085
    // Set
8086
    window->Collapsed = collapsed;
8087
}
8088
8089
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8090
{
8091
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8092
    window->HitTestHoleSize = ImVec2ih(size);
8093
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8094
}
8095
8096
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8097
{
8098
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8099
}
8100
8101
bool ImGui::IsWindowCollapsed()
8102
{
8103
    ImGuiWindow* window = GetCurrentWindowRead();
8104
    return window->Collapsed;
8105
}
8106
8107
bool ImGui::IsWindowAppearing()
8108
{
8109
    ImGuiWindow* window = GetCurrentWindowRead();
8110
    return window->Appearing;
8111
}
8112
8113
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8114
{
8115
    if (ImGuiWindow* window = FindWindowByName(name))
8116
        SetWindowCollapsed(window, collapsed, cond);
8117
}
8118
8119
void ImGui::SetWindowFocus()
8120
{
8121
    FocusWindow(GImGui->CurrentWindow);
8122
}
8123
8124
void ImGui::SetWindowFocus(const char* name)
8125
{
8126
    if (name)
8127
    {
8128
        if (ImGuiWindow* window = FindWindowByName(name))
8129
            FocusWindow(window);
8130
    }
8131
    else
8132
    {
8133
        FocusWindow(NULL);
8134
    }
8135
}
8136
8137
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8138
{
8139
    ImGuiContext& g = *GImGui;
8140
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8141
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8142
    g.NextWindowData.PosVal = pos;
8143
    g.NextWindowData.PosPivotVal = pivot;
8144
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8145
    g.NextWindowData.PosUndock = true;
8146
}
8147
8148
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8149
{
8150
    ImGuiContext& g = *GImGui;
8151
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8152
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8153
    g.NextWindowData.SizeVal = size;
8154
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8155
}
8156
8157
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8158
{
8159
    ImGuiContext& g = *GImGui;
8160
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8161
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8162
    g.NextWindowData.SizeCallback = custom_callback;
8163
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8164
}
8165
8166
// Content size = inner scrollable rectangle, padded with WindowPadding.
8167
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8168
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8169
{
8170
    ImGuiContext& g = *GImGui;
8171
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8172
    g.NextWindowData.ContentSizeVal = ImFloor(size);
8173
}
8174
8175
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8176
{
8177
    ImGuiContext& g = *GImGui;
8178
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8179
    g.NextWindowData.ScrollVal = scroll;
8180
}
8181
8182
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8183
{
8184
    ImGuiContext& g = *GImGui;
8185
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8186
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8187
    g.NextWindowData.CollapsedVal = collapsed;
8188
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8189
}
8190
8191
void ImGui::SetNextWindowFocus()
8192
{
8193
    ImGuiContext& g = *GImGui;
8194
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8195
}
8196
8197
void ImGui::SetNextWindowBgAlpha(float alpha)
8198
{
8199
    ImGuiContext& g = *GImGui;
8200
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8201
    g.NextWindowData.BgAlphaVal = alpha;
8202
}
8203
8204
void ImGui::SetNextWindowViewport(ImGuiID id)
8205
{
8206
    ImGuiContext& g = *GImGui;
8207
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8208
    g.NextWindowData.ViewportId = id;
8209
}
8210
8211
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8212
{
8213
    ImGuiContext& g = *GImGui;
8214
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8215
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8216
    g.NextWindowData.DockId = id;
8217
}
8218
8219
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8220
{
8221
    ImGuiContext& g = *GImGui;
8222
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8223
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8224
    g.NextWindowData.WindowClass = *window_class;
8225
}
8226
8227
ImDrawList* ImGui::GetWindowDrawList()
8228
{
8229
    ImGuiWindow* window = GetCurrentWindow();
8230
    return window->DrawList;
8231
}
8232
8233
float ImGui::GetWindowDpiScale()
8234
{
8235
    ImGuiContext& g = *GImGui;
8236
    return g.CurrentDpiScale;
8237
}
8238
8239
ImGuiViewport* ImGui::GetWindowViewport()
8240
{
8241
    ImGuiContext& g = *GImGui;
8242
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8243
    return g.CurrentViewport;
8244
}
8245
8246
ImFont* ImGui::GetFont()
8247
{
8248
    return GImGui->Font;
8249
}
8250
8251
float ImGui::GetFontSize()
8252
{
8253
    return GImGui->FontSize;
8254
}
8255
8256
ImVec2 ImGui::GetFontTexUvWhitePixel()
8257
{
8258
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8259
}
8260
8261
void ImGui::SetWindowFontScale(float scale)
8262
{
8263
    IM_ASSERT(scale > 0.0f);
8264
    ImGuiContext& g = *GImGui;
8265
    ImGuiWindow* window = GetCurrentWindow();
8266
    window->FontWindowScale = scale;
8267
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8268
}
8269
8270
void ImGui::ActivateItem(ImGuiID id)
8271
{
8272
    ImGuiContext& g = *GImGui;
8273
    g.NavNextActivateId = id;
8274
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8275
}
8276
8277
void ImGui::PushFocusScope(ImGuiID id)
8278
{
8279
    ImGuiContext& g = *GImGui;
8280
    g.FocusScopeStack.push_back(id);
8281
    g.CurrentFocusScopeId = id;
8282
}
8283
8284
void ImGui::PopFocusScope()
8285
{
8286
    ImGuiContext& g = *GImGui;
8287
    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
8288
    g.FocusScopeStack.pop_back();
8289
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back() : 0;
8290
}
8291
8292
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8293
void ImGui::SetKeyboardFocusHere(int offset)
8294
{
8295
    ImGuiContext& g = *GImGui;
8296
    ImGuiWindow* window = g.CurrentWindow;
8297
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8298
    IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8299
8300
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8301
    // When we refactor this function into ActivateItem() we may want to make this an option.
8302
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8303
    // is also automatically dropped in the event g.ActiveId is stolen.
8304
    if (g.DragDropActive || g.MovingWindow != NULL)
8305
    {
8306
        IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8307
        return;
8308
    }
8309
8310
    SetNavWindow(window);
8311
8312
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8313
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_FocusApi, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8314
    if (offset == -1)
8315
    {
8316
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8317
    }
8318
    else
8319
    {
8320
        g.NavTabbingDir = 1;
8321
        g.NavTabbingCounter = offset + 1;
8322
    }
8323
}
8324
8325
void ImGui::SetItemDefaultFocus()
8326
{
8327
    ImGuiContext& g = *GImGui;
8328
    ImGuiWindow* window = g.CurrentWindow;
8329
    if (!window->Appearing)
8330
        return;
8331
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResultId == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8332
        return;
8333
8334
    g.NavInitRequest = false;
8335
    g.NavInitResultId = g.LastItemData.ID;
8336
    g.NavInitResultRectRel = WindowRectAbsToRel(window, g.LastItemData.Rect);
8337
    NavUpdateAnyRequestFlag();
8338
8339
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8340
    if (!IsItemVisible())
8341
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8342
}
8343
8344
void ImGui::SetStateStorage(ImGuiStorage* tree)
8345
{
8346
    ImGuiWindow* window = GImGui->CurrentWindow;
8347
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8348
}
8349
8350
ImGuiStorage* ImGui::GetStateStorage()
8351
{
8352
    ImGuiWindow* window = GImGui->CurrentWindow;
8353
    return window->DC.StateStorage;
8354
}
8355
8356
void ImGui::PushID(const char* str_id)
8357
{
8358
    ImGuiContext& g = *GImGui;
8359
    ImGuiWindow* window = g.CurrentWindow;
8360
    ImGuiID id = window->GetID(str_id);
8361
    window->IDStack.push_back(id);
8362
}
8363
8364
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8365
{
8366
    ImGuiContext& g = *GImGui;
8367
    ImGuiWindow* window = g.CurrentWindow;
8368
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8369
    window->IDStack.push_back(id);
8370
}
8371
8372
void ImGui::PushID(const void* ptr_id)
8373
{
8374
    ImGuiContext& g = *GImGui;
8375
    ImGuiWindow* window = g.CurrentWindow;
8376
    ImGuiID id = window->GetID(ptr_id);
8377
    window->IDStack.push_back(id);
8378
}
8379
8380
void ImGui::PushID(int int_id)
8381
{
8382
    ImGuiContext& g = *GImGui;
8383
    ImGuiWindow* window = g.CurrentWindow;
8384
    ImGuiID id = window->GetID(int_id);
8385
    window->IDStack.push_back(id);
8386
}
8387
8388
// Push a given id value ignoring the ID stack as a seed.
8389
void ImGui::PushOverrideID(ImGuiID id)
8390
{
8391
    ImGuiContext& g = *GImGui;
8392
    ImGuiWindow* window = g.CurrentWindow;
8393
    if (g.DebugHookIdInfo == id)
8394
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8395
    window->IDStack.push_back(id);
8396
}
8397
8398
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8399
// (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
8400
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8401
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8402
{
8403
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8404
    ImGuiContext& g = *GImGui;
8405
    if (g.DebugHookIdInfo == id)
8406
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8407
    return id;
8408
}
8409
8410
void ImGui::PopID()
8411
{
8412
    ImGuiWindow* window = GImGui->CurrentWindow;
8413
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8414
    window->IDStack.pop_back();
8415
}
8416
8417
ImGuiID ImGui::GetID(const char* str_id)
8418
{
8419
    ImGuiWindow* window = GImGui->CurrentWindow;
8420
    return window->GetID(str_id);
8421
}
8422
8423
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8424
{
8425
    ImGuiWindow* window = GImGui->CurrentWindow;
8426
    return window->GetID(str_id_begin, str_id_end);
8427
}
8428
8429
ImGuiID ImGui::GetID(const void* ptr_id)
8430
{
8431
    ImGuiWindow* window = GImGui->CurrentWindow;
8432
    return window->GetID(ptr_id);
8433
}
8434
8435
bool ImGui::IsRectVisible(const ImVec2& size)
8436
{
8437
    ImGuiWindow* window = GImGui->CurrentWindow;
8438
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8439
}
8440
8441
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8442
{
8443
    ImGuiWindow* window = GImGui->CurrentWindow;
8444
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8445
}
8446
8447
8448
//-----------------------------------------------------------------------------
8449
// [SECTION] INPUTS
8450
//-----------------------------------------------------------------------------
8451
8452
// Test if mouse cursor is hovering given rectangle
8453
// NB- Rectangle is clipped by our current clip setting
8454
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
8455
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
8456
{
8457
    ImGuiContext& g = *GImGui;
8458
8459
    // Clip
8460
    ImRect rect_clipped(r_min, r_max);
8461
    if (clip)
8462
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
8463
8464
    // Expand for touch input
8465
    const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
8466
    if (!rect_for_touch.Contains(g.IO.MousePos))
8467
        return false;
8468
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
8469
        return false;
8470
    return true;
8471
}
8472
8473
ImGuiKeyData* ImGui::GetKeyData(ImGuiKey key)
8474
{
8475
    ImGuiContext& g = *GImGui;
8476
8477
    // Special storage location for mods
8478
    if (key & ImGuiMod_Mask_)
8479
        key = ConvertSingleModFlagToKey(key);
8480
8481
    int index;
8482
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8483
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8484
    if (IsLegacyKey(key))
8485
        index = (g.IO.KeyMap[key] != -1) ? g.IO.KeyMap[key] : key; // Remap native->imgui or imgui->native
8486
    else
8487
        index = key;
8488
#else
8489
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8490
    index = key - ImGuiKey_NamedKey_BEGIN;
8491
#endif
8492
    return &g.IO.KeysData[index];
8493
}
8494
8495
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8496
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8497
{
8498
    ImGuiContext& g = *GImGui;
8499
    IM_ASSERT(IsNamedKey(key));
8500
    const ImGuiKeyData* key_data = GetKeyData(key);
8501
    return (ImGuiKey)(key_data - g.IO.KeysData);
8502
}
8503
#endif
8504
8505
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8506
static const char* const GKeyNames[] =
8507
{
8508
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8509
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8510
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8511
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8512
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8513
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8514
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8515
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8516
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8517
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8518
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8519
    "GamepadStart", "GamepadBack",
8520
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8521
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8522
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8523
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8524
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8525
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8526
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8527
};
8528
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8529
8530
const char* ImGui::GetKeyName(ImGuiKey key)
8531
{
8532
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8533
    IM_ASSERT((IsNamedKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8534
#else
8535
    if (IsLegacyKey(key))
8536
    {
8537
        ImGuiIO& io = GetIO();
8538
        if (io.KeyMap[key] == -1)
8539
            return "N/A";
8540
        IM_ASSERT(IsNamedKey((ImGuiKey)io.KeyMap[key]));
8541
        key = (ImGuiKey)io.KeyMap[key];
8542
    }
8543
#endif
8544
    if (key == ImGuiKey_None)
8545
        return "None";
8546
    if (key & ImGuiMod_Mask_)
8547
        key = ConvertSingleModFlagToKey(key);
8548
    if (!IsNamedKey(key))
8549
        return "Unknown";
8550
8551
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8552
}
8553
8554
void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
8555
{
8556
    ImGuiContext& g = *GImGui;
8557
    ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
8558
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8559
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8560
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8561
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8562
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8563
}
8564
8565
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8566
// t1 = current time (e.g.: g.Time)
8567
// An event is triggered at:
8568
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8569
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8570
{
8571
    if (t1 == 0.0f)
8572
        return 1;
8573
    if (t0 >= t1)
8574
        return 0;
8575
    if (repeat_rate <= 0.0f)
8576
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8577
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8578
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8579
    const int count = count_t1 - count_t0;
8580
    return count;
8581
}
8582
8583
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8584
{
8585
    ImGuiContext& g = *GImGui;
8586
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8587
    {
8588
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8589
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8590
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8591
    }
8592
}
8593
8594
// Return value representing the number of presses in the last time period, for the given repeat rate
8595
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8596
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8597
{
8598
    ImGuiContext& g = *GImGui;
8599
    const ImGuiKeyData* key_data = GetKeyData(key);
8600
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8601
        return 0;
8602
    const float t = key_data->DownDuration;
8603
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8604
}
8605
8606
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8607
ImVec2 ImGui::GetKeyVector2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8608
{
8609
    return ImVec2(
8610
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8611
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8612
}
8613
8614
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8615
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8616
{
8617
    ImGuiContext& g = *GImGui;
8618
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8619
}
8620
8621
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8622
{
8623
    // Majority of shortcuts will be Key + any number of Mods
8624
    // We accept _Single_ mod with ImGuiKey_None.
8625
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
8626
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
8627
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
8628
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
8629
    ImGuiContext& g = *GImGui;
8630
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8631
    ImGuiKeyRoutingData* routing_data;
8632
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8633
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8634
    if (key == ImGuiKey_None)
8635
        key = ConvertSingleModFlagToKey(mods);
8636
    IM_ASSERT(IsNamedKey(key));
8637
8638
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8639
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8640
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8641
    {
8642
        routing_data = &rt->Entries[idx];
8643
        if (routing_data->Mods == mods)
8644
            return routing_data;
8645
    }
8646
8647
    // Add to linked-list
8648
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8649
    rt->Entries.push_back(ImGuiKeyRoutingData());
8650
    routing_data = &rt->Entries[routing_data_idx];
8651
    routing_data->Mods = (ImU16)mods;
8652
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8653
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8654
    return routing_data;
8655
}
8656
8657
// Current score encoding (lower is highest priority):
8658
//  -   0: ImGuiInputFlags_RouteGlobalHigh
8659
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
8660
//  -   2: ImGuiInputFlags_RouteGlobal
8661
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8662
//  - 254: ImGuiInputFlags_RouteGlobalLow
8663
//  - 255: never route
8664
// 'flags' should include an explicit routing policy
8665
static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputFlags flags)
8666
{
8667
    if (flags & ImGuiInputFlags_RouteFocused)
8668
    {
8669
        ImGuiContext& g = *GImGui;
8670
        ImGuiWindow* focused = g.NavWindow;
8671
8672
        // ActiveID gets top priority
8673
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8674
        if (owner_id != 0 && g.ActiveId == owner_id)
8675
            return 1;
8676
8677
        // Score based on distance to focused window (lower is better)
8678
        // Assuming both windows are submitting a routing request,
8679
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8680
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
8681
        // Assuming only WindowA is submitting a routing request,
8682
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8683
        if (focused != NULL && focused->RootWindow == location->RootWindow)
8684
            for (int next_score = 3; focused != NULL; next_score++)
8685
            {
8686
                if (focused == location)
8687
                {
8688
                    IM_ASSERT(next_score < 255);
8689
                    return next_score;
8690
                }
8691
                focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path
8692
            }
8693
        return 255;
8694
    }
8695
8696
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
8697
    if (flags & ImGuiInputFlags_RouteGlobal)
8698
        return 2;
8699
    if (flags & ImGuiInputFlags_RouteGlobalLow)
8700
        return 254;
8701
    return 0;
8702
}
8703
8704
// Request a desired route for an input chord (key + mods).
8705
// Return true if the route is available this frame.
8706
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8707
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
8708
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8709
// - Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
8710
// - Using 'owner_id == ImGuiKeyOwner_None': allows disabling/locking a shortcut.
8711
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
8712
{
8713
    ImGuiContext& g = *GImGui;
8714
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
8715
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8716
    else
8717
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
8718
8719
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8720
        if (g.NavWindow == NULL)
8721
            return false;
8722
    if (flags & ImGuiInputFlags_RouteAlways)
8723
        return true;
8724
8725
    const int score = CalcRoutingScore(g.CurrentWindow, owner_id, flags);
8726
    if (score == 255)
8727
        return false;
8728
8729
    // Submit routing for NEXT frame (assuming score is sufficient)
8730
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8731
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8732
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8733
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8734
    if (score < routing_data->RoutingNextScore)
8735
    {
8736
        routing_data->RoutingNext = routing_id;
8737
        routing_data->RoutingNextScore = (ImU8)score;
8738
    }
8739
8740
    // Return routing state for CURRENT frame
8741
    return routing_data->RoutingCurr == routing_id;
8742
}
8743
8744
// Currently unused by core (but used by tests)
8745
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8746
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8747
{
8748
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8749
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8750
    return routing_data->RoutingCurr == routing_id;
8751
}
8752
8753
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8754
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8755
bool ImGui::IsKeyDown(ImGuiKey key)
8756
{
8757
    return IsKeyDown(key, ImGuiKeyOwner_Any);
8758
}
8759
8760
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
8761
{
8762
    const ImGuiKeyData* key_data = GetKeyData(key);
8763
    if (!key_data->Down)
8764
        return false;
8765
    if (!TestKeyOwner(key, owner_id))
8766
        return false;
8767
    return true;
8768
}
8769
8770
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
8771
{
8772
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8773
}
8774
8775
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
8776
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
8777
{
8778
    const ImGuiKeyData* key_data = GetKeyData(key);
8779
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8780
        return false;
8781
    const float t = key_data->DownDuration;
8782
    if (t < 0.0f)
8783
        return false;
8784
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8785
8786
    bool pressed = (t == 0.0f);
8787
    if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
8788
    {
8789
        float repeat_delay, repeat_rate;
8790
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
8791
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
8792
    }
8793
    if (!pressed)
8794
        return false;
8795
    if (!TestKeyOwner(key, owner_id))
8796
        return false;
8797
    return true;
8798
}
8799
8800
bool ImGui::IsKeyReleased(ImGuiKey key)
8801
{
8802
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
8803
}
8804
8805
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
8806
{
8807
    const ImGuiKeyData* key_data = GetKeyData(key);
8808
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
8809
        return false;
8810
    if (!TestKeyOwner(key, owner_id))
8811
        return false;
8812
    return true;
8813
}
8814
8815
bool ImGui::IsMouseDown(ImGuiMouseButton button)
8816
{
8817
    ImGuiContext& g = *GImGui;
8818
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8819
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
8820
}
8821
8822
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
8823
{
8824
    ImGuiContext& g = *GImGui;
8825
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8826
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
8827
}
8828
8829
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
8830
{
8831
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8832
}
8833
8834
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
8835
{
8836
    ImGuiContext& g = *GImGui;
8837
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8838
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8839
        return false;
8840
    const float t = g.IO.MouseDownDuration[button];
8841
    if (t < 0.0f)
8842
        return false;
8843
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8844
8845
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
8846
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
8847
    if (!pressed)
8848
        return false;
8849
8850
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
8851
        return false;
8852
8853
    return true;
8854
}
8855
8856
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
8857
{
8858
    ImGuiContext& g = *GImGui;
8859
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8860
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
8861
}
8862
8863
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
8864
{
8865
    ImGuiContext& g = *GImGui;
8866
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8867
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
8868
}
8869
8870
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
8871
{
8872
    ImGuiContext& g = *GImGui;
8873
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8874
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
8875
}
8876
8877
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
8878
{
8879
    ImGuiContext& g = *GImGui;
8880
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8881
    return g.IO.MouseClickedCount[button];
8882
}
8883
8884
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
8885
// [Internal] This doesn't test if the button is pressed
8886
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
8887
{
8888
    ImGuiContext& g = *GImGui;
8889
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8890
    if (lock_threshold < 0.0f)
8891
        lock_threshold = g.IO.MouseDragThreshold;
8892
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
8893
}
8894
8895
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
8896
{
8897
    ImGuiContext& g = *GImGui;
8898
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8899
    if (!g.IO.MouseDown[button])
8900
        return false;
8901
    return IsMouseDragPastThreshold(button, lock_threshold);
8902
}
8903
8904
ImVec2 ImGui::GetMousePos()
8905
{
8906
    ImGuiContext& g = *GImGui;
8907
    return g.IO.MousePos;
8908
}
8909
8910
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
8911
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
8912
{
8913
    ImGuiContext& g = *GImGui;
8914
    if (g.BeginPopupStack.Size > 0)
8915
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
8916
    return g.IO.MousePos;
8917
}
8918
8919
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
8920
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
8921
{
8922
    // The assert is only to silence a false-positive in XCode Static Analysis.
8923
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
8924
    IM_ASSERT(GImGui != NULL);
8925
    const float MOUSE_INVALID = -256000.0f;
8926
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
8927
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
8928
}
8929
8930
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
8931
bool ImGui::IsAnyMouseDown()
8932
{
8933
    ImGuiContext& g = *GImGui;
8934
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
8935
        if (g.IO.MouseDown[n])
8936
            return true;
8937
    return false;
8938
}
8939
8940
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
8941
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
8942
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
8943
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
8944
{
8945
    ImGuiContext& g = *GImGui;
8946
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8947
    if (lock_threshold < 0.0f)
8948
        lock_threshold = g.IO.MouseDragThreshold;
8949
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
8950
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
8951
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
8952
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
8953
    return ImVec2(0.0f, 0.0f);
8954
}
8955
8956
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
8957
{
8958
    ImGuiContext& g = *GImGui;
8959
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8960
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
8961
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
8962
}
8963
8964
// Get desired mouse cursor shape.
8965
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
8966
// updated during the frame, and locked in EndFrame()/Render().
8967
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
8968
ImGuiMouseCursor ImGui::GetMouseCursor()
8969
{
8970
    ImGuiContext& g = *GImGui;
8971
    return g.MouseCursor;
8972
}
8973
8974
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
8975
{
8976
    ImGuiContext& g = *GImGui;
8977
    g.MouseCursor = cursor_type;
8978
}
8979
8980
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
8981
{
8982
    ImGuiContext& g = *GImGui;
8983
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
8984
}
8985
8986
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
8987
{
8988
    ImGuiContext& g = *GImGui;
8989
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
8990
}
8991
8992
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8993
static const char* GetInputSourceName(ImGuiInputSource source)
8994
{
8995
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Nav", "Clipboard" };
8996
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
8997
    return input_source_names[source];
8998
}
8999
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9000
{
9001
    ImGuiContext& g = *GImGui;
9002
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("%s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("%s: MousePos (%.1f, %.1f)\n", prefix, e->MousePos.PosX, e->MousePos.PosY); return; }
9003
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("%s: MouseButton %d %s\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up"); return; }
9004
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("%s: MouseWheel (%.1f, %.1f)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY); return; }
9005
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("%s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9006
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("%s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9007
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("%s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9008
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("%s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9009
}
9010
#endif
9011
9012
// Process input queue
9013
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9014
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9015
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9016
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9017
{
9018
    ImGuiContext& g = *GImGui;
9019
    ImGuiIO& io = g.IO;
9020
9021
    // Only trickle chars<>key when working with InputText()
9022
    // FIXME: InputText() could parse event trail?
9023
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9024
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9025
9026
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9027
    int  mouse_button_changed = 0x00;
9028
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9029
9030
    int event_n = 0;
9031
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9032
    {
9033
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9034
        if (e->Type == ImGuiInputEventType_MousePos)
9035
        {
9036
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9037
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9038
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9039
                break;
9040
            io.MousePos = event_pos;
9041
            mouse_moved = true;
9042
        }
9043
        else if (e->Type == ImGuiInputEventType_MouseButton)
9044
        {
9045
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9046
            const ImGuiMouseButton button = e->MouseButton.Button;
9047
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9048
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9049
                break;
9050
            io.MouseDown[button] = e->MouseButton.Down;
9051
            mouse_button_changed |= (1 << button);
9052
        }
9053
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9054
        {
9055
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9056
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9057
                break;
9058
            io.MouseWheelH += e->MouseWheel.WheelX;
9059
            io.MouseWheel += e->MouseWheel.WheelY;
9060
            mouse_wheeled = true;
9061
        }
9062
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9063
        {
9064
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9065
        }
9066
        else if (e->Type == ImGuiInputEventType_Key)
9067
        {
9068
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9069
            ImGuiKey key = e->Key.Key;
9070
            IM_ASSERT(key != ImGuiKey_None);
9071
            ImGuiKeyData* key_data = GetKeyData(key);
9072
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9073
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9074
                break;
9075
            key_data->Down = e->Key.Down;
9076
            key_data->AnalogValue = e->Key.AnalogValue;
9077
            key_changed = true;
9078
            key_changed_mask.SetBit(key_data_index);
9079
9080
            if (key == ImGuiMod_Ctrl || key == ImGuiMod_Shift || key == ImGuiMod_Alt || key == ImGuiMod_Super)
9081
            {
9082
                if (key == ImGuiMod_Ctrl) { io.KeyCtrl = key_data->Down; }
9083
                if (key == ImGuiMod_Shift) { io.KeyShift = key_data->Down; }
9084
                if (key == ImGuiMod_Alt) { io.KeyAlt = key_data->Down; }
9085
                if (key == ImGuiMod_Super) { io.KeySuper = key_data->Down; }
9086
                io.KeyMods = GetMergedModsFromBools();
9087
            }
9088
9089
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9090
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9091
            io.KeysDown[key_data_index] = key_data->Down;
9092
            if (io.KeyMap[key_data_index] != -1)
9093
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9094
#endif
9095
        }
9096
        else if (e->Type == ImGuiInputEventType_Text)
9097
        {
9098
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9099
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9100
                break;
9101
            unsigned int c = e->Text.Char;
9102
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9103
            if (trickle_interleaved_keys_and_text)
9104
                text_inputted = true;
9105
        }
9106
        else if (e->Type == ImGuiInputEventType_Focus)
9107
        {
9108
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9109
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9110
            const bool focus_lost = !e->AppFocused.Focused;
9111
            io.AppFocusLost = focus_lost;
9112
        }
9113
        else
9114
        {
9115
            IM_ASSERT(0 && "Unknown event!");
9116
        }
9117
    }
9118
9119
    // Record trail (for domain-specific applications wanting to access a precise trail)
9120
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9121
    for (int n = 0; n < event_n; n++)
9122
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9123
9124
    // [DEBUG]
9125
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9126
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9127
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9128
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9129
#endif
9130
9131
    // Remaining events will be processed on the next frame
9132
    if (event_n == g.InputEventsQueue.Size)
9133
        g.InputEventsQueue.resize(0);
9134
    else
9135
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9136
9137
    // Clear buttons state when focus is lost
9138
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9139
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9140
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9141
    if (g.IO.AppFocusLost)
9142
        g.IO.ClearInputKeys();
9143
}
9144
9145
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9146
{
9147
    if (!IsNamedKeyOrModKey(key))
9148
        return ImGuiKeyOwner_None;
9149
9150
    ImGuiContext& g = *GImGui;
9151
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
9152
    ImGuiID owner_id = owner_data->OwnerCurr;
9153
9154
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9155
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9156
            return ImGuiKeyOwner_None;
9157
9158
    return owner_id;
9159
}
9160
9161
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
9162
// TestKeyOwner(..., None) : (owner == None)
9163
// TestKeyOwner(..., Any)  : no owner test
9164
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9165
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9166
{
9167
    if (!IsNamedKeyOrModKey(key))
9168
        return true;
9169
9170
    ImGuiContext& g = *GImGui;
9171
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9172
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9173
            return false;
9174
9175
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
9176
    if (owner_id == ImGuiKeyOwner_Any)
9177
        return (owner_data->LockThisFrame == false);
9178
9179
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9180
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9181
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9182
    if (owner_data->OwnerCurr != owner_id)
9183
    {
9184
        if (owner_data->LockThisFrame)
9185
            return false;
9186
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
9187
            return false;
9188
    }
9189
9190
    return true;
9191
}
9192
9193
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9194
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9195
// - SetKeyOwner(..., None)              : clears owner
9196
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
9197
// - SetKeyOwner(..., Any or None, Lock) : set lock
9198
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9199
{
9200
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9201
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9202
9203
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
9204
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9205
9206
    // We cannot lock by default as it would likely break lots of legacy code.
9207
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9208
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9209
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9210
}
9211
9212
// This is more or less equivalent to:
9213
//   if (IsItemHovered() || IsItemActive())
9214
//       SetKeyOwner(key, GetItemID());
9215
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
9216
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9217
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
9218
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9219
{
9220
    ImGuiContext& g = *GImGui;
9221
    ImGuiID id = g.LastItemData.ID;
9222
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9223
        return;
9224
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
9225
        flags |= ImGuiInputFlags_CondDefault_;
9226
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9227
    {
9228
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9229
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
9230
    }
9231
}
9232
9233
// - Need to decide how to handle shortcut translations for Non-Mac <> Mac
9234
// - Ideas: https://github.com/ocornut/imgui/issues/456#issuecomment-264390864
9235
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9236
{
9237
    ImGuiContext& g = *GImGui;
9238
9239
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9240
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9241
        flags |= ImGuiInputFlags_RouteFocused;
9242
    if (!SetShortcutRouting(key_chord, owner_id, flags))
9243
        return false;
9244
9245
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9246
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9247
    if (g.IO.KeyMods != mods)
9248
        return false;
9249
9250
    // Special storage location for mods
9251
    if (key == ImGuiKey_None)
9252
        key = ConvertSingleModFlagToKey(mods);
9253
9254
    if (!IsKeyPressed(key, owner_id, (flags & (ImGuiInputFlags_Repeat | ImGuiInputFlags_RepeatRateMask_))))
9255
        return false;
9256
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9257
9258
    return true;
9259
}
9260
9261
9262
//-----------------------------------------------------------------------------
9263
// [SECTION] ERROR CHECKING
9264
//-----------------------------------------------------------------------------
9265
9266
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
9267
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9268
// If this triggers you have an issue:
9269
// - Most commonly: mismatched headers and compiled code version.
9270
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
9271
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
9272
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
9273
//   Otherwise it is possible that different compilation units would see different structure layout
9274
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
9275
{
9276
    bool error = false;
9277
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9278
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9279
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9280
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9281
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9282
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9283
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9284
    return !error;
9285
}
9286
9287
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
9288
// This is causing issues and ambiguity and we need to retire that.
9289
// See https://github.com/ocornut/imgui/issues/5548 for more details.
9290
// [Scenario 1]
9291
//  Previously this would make the window content size ~200x200:
9292
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
9293
//  Instead, please submit an item:
9294
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9295
//  Alternative:
9296
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9297
// [Scenario 2]
9298
//  For reference this is one of the issue what we aim to fix with this change:
9299
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9300
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
9301
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
9302
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9303
{
9304
    ImGuiContext& g = *GImGui;
9305
    ImGuiWindow* window = g.CurrentWindow;
9306
    IM_ASSERT(window->DC.IsSetPos);
9307
    window->DC.IsSetPos = false;
9308
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9309
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9310
        return;
9311
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9312
#else
9313
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9314
#endif
9315
}
9316
9317
static void ImGui::ErrorCheckNewFrameSanityChecks()
9318
{
9319
    ImGuiContext& g = *GImGui;
9320
9321
    // Check user IM_ASSERT macro
9322
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9323
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9324
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9325
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
9326
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
9327
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
9328
9329
    // Check user data
9330
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
9331
    IM_ASSERT(g.Initialized);
9332
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
9333
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
9334
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
9335
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
9336
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
9337
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
9338
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
9339
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
9340
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
9341
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
9342
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9343
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
9344
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
9345
9346
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
9347
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
9348
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
9349
#endif
9350
9351
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
9352
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
9353
        g.IO.ConfigWindowsResizeFromEdges = false;
9354
9355
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
9356
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
9357
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9358
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
9359
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9360
9361
    // Perform simple checks: multi-viewport and platform windows support
9362
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
9363
    {
9364
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
9365
        {
9366
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
9367
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
9368
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
9369
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
9370
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
9371
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
9372
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
9373
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
9374
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
9375
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
9376
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
9377
        }
9378
        else
9379
        {
9380
            // Disable feature, our backends do not support it
9381
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
9382
        }
9383
9384
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
9385
        for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
9386
        {
9387
            ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n];
9388
            IM_UNUSED(mon);
9389
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
9390
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
9391
            IM_ASSERT(mon.DpiScale != 0.0f);
9392
        }
9393
    }
9394
}
9395
9396
static void ImGui::ErrorCheckEndFrameSanityChecks()
9397
{
9398
    ImGuiContext& g = *GImGui;
9399
9400
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
9401
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
9402
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
9403
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
9404
    // We silently accommodate for this case by ignoring/ the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
9405
    // while still correctly asserting on mid-frame key press events.
9406
    const ImGuiKeyChord key_mods = GetMergedModsFromBools();
9407
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
9408
    IM_UNUSED(key_mods);
9409
9410
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
9411
    //ErrorCheckEndFrameRecover();
9412
9413
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
9414
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
9415
    if (g.CurrentWindowStack.Size != 1)
9416
    {
9417
        if (g.CurrentWindowStack.Size > 1)
9418
        {
9419
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
9420
            while (g.CurrentWindowStack.Size > 1)
9421
                End();
9422
        }
9423
        else
9424
        {
9425
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
9426
        }
9427
    }
9428
9429
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
9430
}
9431
9432
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
9433
// Must be called during or before EndFrame().
9434
// This is generally flawed as we are not necessarily End/Popping things in the right order.
9435
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
9436
// FIXME: Can't recover from interleaved BeginTabBar/Begin
9437
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9438
{
9439
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
9440
    ImGuiContext& g = *GImGui;
9441
    while (g.CurrentWindowStack.Size > 0) //-V1044
9442
    {
9443
        ErrorCheckEndWindowRecover(log_callback, user_data);
9444
        ImGuiWindow* window = g.CurrentWindow;
9445
        if (g.CurrentWindowStack.Size == 1)
9446
        {
9447
            IM_ASSERT(window->IsFallbackWindow);
9448
            break;
9449
        }
9450
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
9451
        {
9452
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
9453
            EndChild();
9454
        }
9455
        else
9456
        {
9457
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
9458
            End();
9459
        }
9460
    }
9461
}
9462
9463
// Must be called before End()/EndChild()
9464
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9465
{
9466
    ImGuiContext& g = *GImGui;
9467
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
9468
    {
9469
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
9470
        EndTable();
9471
    }
9472
9473
    ImGuiWindow* window = g.CurrentWindow;
9474
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
9475
    IM_ASSERT(window != NULL);
9476
    while (g.CurrentTabBar != NULL) //-V1044
9477
    {
9478
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
9479
        EndTabBar();
9480
    }
9481
    while (window->DC.TreeDepth > 0)
9482
    {
9483
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
9484
        TreePop();
9485
    }
9486
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
9487
    {
9488
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
9489
        EndGroup();
9490
    }
9491
    while (window->IDStack.Size > 1)
9492
    {
9493
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
9494
        PopID();
9495
    }
9496
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
9497
    {
9498
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
9499
        EndDisabled();
9500
    }
9501
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
9502
    {
9503
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
9504
        PopStyleColor();
9505
    }
9506
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
9507
    {
9508
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
9509
        PopItemFlag();
9510
    }
9511
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
9512
    {
9513
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
9514
        PopStyleVar();
9515
    }
9516
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
9517
    {
9518
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
9519
        PopFocusScope();
9520
    }
9521
}
9522
9523
// Save current stack sizes for later compare
9524
void ImGuiStackSizes::SetToCurrentState()
9525
{
9526
    ImGuiContext& g = *GImGui;
9527
    ImGuiWindow* window = g.CurrentWindow;
9528
    SizeOfIDStack = (short)window->IDStack.Size;
9529
    SizeOfColorStack = (short)g.ColorStack.Size;
9530
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
9531
    SizeOfFontStack = (short)g.FontStack.Size;
9532
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
9533
    SizeOfGroupStack = (short)g.GroupStack.Size;
9534
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
9535
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
9536
    SizeOfDisabledStack = (short)g.DisabledStackSize;
9537
}
9538
9539
// Compare to detect usage errors
9540
void ImGuiStackSizes::CompareWithCurrentState()
9541
{
9542
    ImGuiContext& g = *GImGui;
9543
    ImGuiWindow* window = g.CurrentWindow;
9544
    IM_UNUSED(window);
9545
9546
    // Window stacks
9547
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
9548
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
9549
9550
    // Global stacks
9551
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
9552
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
9553
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
9554
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
9555
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
9556
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
9557
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
9558
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
9559
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
9560
}
9561
9562
9563
//-----------------------------------------------------------------------------
9564
// [SECTION] LAYOUT
9565
//-----------------------------------------------------------------------------
9566
// - ItemSize()
9567
// - ItemAdd()
9568
// - SameLine()
9569
// - GetCursorScreenPos()
9570
// - SetCursorScreenPos()
9571
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
9572
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
9573
// - GetCursorStartPos()
9574
// - Indent()
9575
// - Unindent()
9576
// - SetNextItemWidth()
9577
// - PushItemWidth()
9578
// - PushMultiItemsWidths()
9579
// - PopItemWidth()
9580
// - CalcItemWidth()
9581
// - CalcItemSize()
9582
// - GetTextLineHeight()
9583
// - GetTextLineHeightWithSpacing()
9584
// - GetFrameHeight()
9585
// - GetFrameHeightWithSpacing()
9586
// - GetContentRegionMax()
9587
// - GetContentRegionMaxAbs() [Internal]
9588
// - GetContentRegionAvail(),
9589
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
9590
// - BeginGroup()
9591
// - EndGroup()
9592
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
9593
//-----------------------------------------------------------------------------
9594
9595
// Advance cursor given item size for layout.
9596
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
9597
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
9598
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
9599
{
9600
    ImGuiContext& g = *GImGui;
9601
    ImGuiWindow* window = g.CurrentWindow;
9602
    if (window->SkipItems)
9603
        return;
9604
9605
    // We increase the height in this function to accommodate for baseline offset.
9606
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
9607
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
9608
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
9609
9610
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
9611
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
9612
9613
    // Always align ourselves on pixel boundaries
9614
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
9615
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
9616
    window->DC.CursorPosPrevLine.y = line_y1;
9617
    window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
9618
    window->DC.CursorPos.y = IM_FLOOR(line_y1 + line_height + g.Style.ItemSpacing.y);                    // Next line
9619
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
9620
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
9621
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
9622
9623
    window->DC.PrevLineSize.y = line_height;
9624
    window->DC.CurrLineSize.y = 0.0f;
9625
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
9626
    window->DC.CurrLineTextBaseOffset = 0.0f;
9627
    window->DC.IsSameLine = window->DC.IsSetPos = false;
9628
9629
    // Horizontal layout mode
9630
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
9631
        SameLine();
9632
}
9633
9634
// Declare item bounding box for clipping and interaction.
9635
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
9636
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
9637
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
9638
{
9639
    ImGuiContext& g = *GImGui;
9640
    ImGuiWindow* window = g.CurrentWindow;
9641
9642
    // Set item data
9643
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
9644
    g.LastItemData.ID = id;
9645
    g.LastItemData.Rect = bb;
9646
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
9647
    g.LastItemData.InFlags = g.CurrentItemFlags | extra_flags;
9648
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
9649
9650
    // Directional navigation processing
9651
    if (id != 0)
9652
    {
9653
        KeepAliveID(id);
9654
9655
        // Runs prior to clipping early-out
9656
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
9657
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
9658
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
9659
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
9660
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
9661
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
9662
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
9663
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
9664
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
9665
        {
9666
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
9667
            if (g.NavId == id || g.NavAnyRequest)
9668
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
9669
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
9670
                        NavProcessItem();
9671
        }
9672
9673
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
9674
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
9675
        // READ THE FAQ: https://dearimgui.org/faq
9676
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
9677
    }
9678
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
9679
9680
#ifdef IMGUI_ENABLE_TEST_ENGINE
9681
    if (id != 0)
9682
        IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
9683
#endif
9684
9685
    // Clipping test
9686
    // (FIXME: This is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
9687
    //const bool is_clipped = IsClippedEx(bb, id);
9688
    //if (is_clipped)
9689
    //    return false;
9690
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
9691
    if (!is_rect_visible)
9692
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
9693
            if (!g.LogEnabled)
9694
                return false;
9695
9696
    // [DEBUG]
9697
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9698
    if (id != 0 && id == g.DebugLocateId)
9699
        DebugLocateItemResolveWithLastItem();
9700
#endif
9701
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
9702
9703
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
9704
    if (is_rect_visible)
9705
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
9706
    if (IsMouseHoveringRect(bb.Min, bb.Max))
9707
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
9708
    return true;
9709
}
9710
9711
// Gets back to previous line and continue with horizontal layout
9712
//      offset_from_start_x == 0 : follow right after previous item
9713
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
9714
//      spacing_w < 0            : use default spacing if pos_x == 0, no spacing if pos_x != 0
9715
//      spacing_w >= 0           : enforce spacing amount
9716
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
9717
{
9718
    ImGuiContext& g = *GImGui;
9719
    ImGuiWindow* window = g.CurrentWindow;
9720
    if (window->SkipItems)
9721
        return;
9722
9723
    if (offset_from_start_x != 0.0f)
9724
    {
9725
        if (spacing_w < 0.0f)
9726
            spacing_w = 0.0f;
9727
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
9728
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
9729
    }
9730
    else
9731
    {
9732
        if (spacing_w < 0.0f)
9733
            spacing_w = g.Style.ItemSpacing.x;
9734
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
9735
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
9736
    }
9737
    window->DC.CurrLineSize = window->DC.PrevLineSize;
9738
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
9739
    window->DC.IsSameLine = true;
9740
}
9741
9742
ImVec2 ImGui::GetCursorScreenPos()
9743
{
9744
    ImGuiWindow* window = GetCurrentWindowRead();
9745
    return window->DC.CursorPos;
9746
}
9747
9748
// 2022/08/05: Setting cursor position also extend boundaries (via modifying CursorMaxPos) used to compute window size, group size etc.
9749
// I believe this was is a judicious choice but it's probably being relied upon (it has been the case since 1.31 and 1.50)
9750
// It would be sane if we requested user to use SetCursorPos() + Dummy(ImVec2(0,0)) to extend CursorMaxPos...
9751
void ImGui::SetCursorScreenPos(const ImVec2& pos)
9752
{
9753
    ImGuiWindow* window = GetCurrentWindow();
9754
    window->DC.CursorPos = pos;
9755
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9756
    window->DC.IsSetPos = true;
9757
}
9758
9759
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
9760
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
9761
ImVec2 ImGui::GetCursorPos()
9762
{
9763
    ImGuiWindow* window = GetCurrentWindowRead();
9764
    return window->DC.CursorPos - window->Pos + window->Scroll;
9765
}
9766
9767
float ImGui::GetCursorPosX()
9768
{
9769
    ImGuiWindow* window = GetCurrentWindowRead();
9770
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
9771
}
9772
9773
float ImGui::GetCursorPosY()
9774
{
9775
    ImGuiWindow* window = GetCurrentWindowRead();
9776
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
9777
}
9778
9779
void ImGui::SetCursorPos(const ImVec2& local_pos)
9780
{
9781
    ImGuiWindow* window = GetCurrentWindow();
9782
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
9783
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9784
    window->DC.IsSetPos = true;
9785
}
9786
9787
void ImGui::SetCursorPosX(float x)
9788
{
9789
    ImGuiWindow* window = GetCurrentWindow();
9790
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
9791
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
9792
    window->DC.IsSetPos = true;
9793
}
9794
9795
void ImGui::SetCursorPosY(float y)
9796
{
9797
    ImGuiWindow* window = GetCurrentWindow();
9798
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
9799
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
9800
    window->DC.IsSetPos = true;
9801
}
9802
9803
ImVec2 ImGui::GetCursorStartPos()
9804
{
9805
    ImGuiWindow* window = GetCurrentWindowRead();
9806
    return window->DC.CursorStartPos - window->Pos;
9807
}
9808
9809
void ImGui::Indent(float indent_w)
9810
{
9811
    ImGuiContext& g = *GImGui;
9812
    ImGuiWindow* window = GetCurrentWindow();
9813
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
9814
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
9815
}
9816
9817
void ImGui::Unindent(float indent_w)
9818
{
9819
    ImGuiContext& g = *GImGui;
9820
    ImGuiWindow* window = GetCurrentWindow();
9821
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
9822
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
9823
}
9824
9825
// Affect large frame+labels widgets only.
9826
void ImGui::SetNextItemWidth(float item_width)
9827
{
9828
    ImGuiContext& g = *GImGui;
9829
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
9830
    g.NextItemData.Width = item_width;
9831
}
9832
9833
// FIXME: Remove the == 0.0f behavior?
9834
void ImGui::PushItemWidth(float item_width)
9835
{
9836
    ImGuiContext& g = *GImGui;
9837
    ImGuiWindow* window = g.CurrentWindow;
9838
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
9839
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
9840
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
9841
}
9842
9843
void ImGui::PushMultiItemsWidths(int components, float w_full)
9844
{
9845
    ImGuiContext& g = *GImGui;
9846
    ImGuiWindow* window = g.CurrentWindow;
9847
    const ImGuiStyle& style = g.Style;
9848
    const float w_item_one  = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
9849
    const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
9850
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
9851
    window->DC.ItemWidthStack.push_back(w_item_last);
9852
    for (int i = 0; i < components - 2; i++)
9853
        window->DC.ItemWidthStack.push_back(w_item_one);
9854
    window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
9855
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
9856
}
9857
9858
void ImGui::PopItemWidth()
9859
{
9860
    ImGuiWindow* window = GetCurrentWindow();
9861
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
9862
    window->DC.ItemWidthStack.pop_back();
9863
}
9864
9865
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
9866
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
9867
float ImGui::CalcItemWidth()
9868
{
9869
    ImGuiContext& g = *GImGui;
9870
    ImGuiWindow* window = g.CurrentWindow;
9871
    float w;
9872
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
9873
        w = g.NextItemData.Width;
9874
    else
9875
        w = window->DC.ItemWidth;
9876
    if (w < 0.0f)
9877
    {
9878
        float region_max_x = GetContentRegionMaxAbs().x;
9879
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
9880
    }
9881
    w = IM_FLOOR(w);
9882
    return w;
9883
}
9884
9885
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
9886
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
9887
// Note that only CalcItemWidth() is publicly exposed.
9888
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
9889
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
9890
{
9891
    ImGuiContext& g = *GImGui;
9892
    ImGuiWindow* window = g.CurrentWindow;
9893
9894
    ImVec2 region_max;
9895
    if (size.x < 0.0f || size.y < 0.0f)
9896
        region_max = GetContentRegionMaxAbs();
9897
9898
    if (size.x == 0.0f)
9899
        size.x = default_w;
9900
    else if (size.x < 0.0f)
9901
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
9902
9903
    if (size.y == 0.0f)
9904
        size.y = default_h;
9905
    else if (size.y < 0.0f)
9906
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
9907
9908
    return size;
9909
}
9910
9911
float ImGui::GetTextLineHeight()
9912
{
9913
    ImGuiContext& g = *GImGui;
9914
    return g.FontSize;
9915
}
9916
9917
float ImGui::GetTextLineHeightWithSpacing()
9918
{
9919
    ImGuiContext& g = *GImGui;
9920
    return g.FontSize + g.Style.ItemSpacing.y;
9921
}
9922
9923
float ImGui::GetFrameHeight()
9924
{
9925
    ImGuiContext& g = *GImGui;
9926
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
9927
}
9928
9929
float ImGui::GetFrameHeightWithSpacing()
9930
{
9931
    ImGuiContext& g = *GImGui;
9932
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
9933
}
9934
9935
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
9936
9937
// FIXME: This is in window space (not screen space!).
9938
ImVec2 ImGui::GetContentRegionMax()
9939
{
9940
    ImGuiContext& g = *GImGui;
9941
    ImGuiWindow* window = g.CurrentWindow;
9942
    ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
9943
    if (window->DC.CurrentColumns || g.CurrentTable)
9944
        mx.x = window->WorkRect.Max.x - window->Pos.x;
9945
    return mx;
9946
}
9947
9948
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
9949
ImVec2 ImGui::GetContentRegionMaxAbs()
9950
{
9951
    ImGuiContext& g = *GImGui;
9952
    ImGuiWindow* window = g.CurrentWindow;
9953
    ImVec2 mx = window->ContentRegionRect.Max;
9954
    if (window->DC.CurrentColumns || g.CurrentTable)
9955
        mx.x = window->WorkRect.Max.x;
9956
    return mx;
9957
}
9958
9959
ImVec2 ImGui::GetContentRegionAvail()
9960
{
9961
    ImGuiWindow* window = GImGui->CurrentWindow;
9962
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
9963
}
9964
9965
// In window space (not screen space!)
9966
ImVec2 ImGui::GetWindowContentRegionMin()
9967
{
9968
    ImGuiWindow* window = GImGui->CurrentWindow;
9969
    return window->ContentRegionRect.Min - window->Pos;
9970
}
9971
9972
ImVec2 ImGui::GetWindowContentRegionMax()
9973
{
9974
    ImGuiWindow* window = GImGui->CurrentWindow;
9975
    return window->ContentRegionRect.Max - window->Pos;
9976
}
9977
9978
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
9979
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
9980
// FIXME-OPT: Could we safely early out on ->SkipItems?
9981
void ImGui::BeginGroup()
9982
{
9983
    ImGuiContext& g = *GImGui;
9984
    ImGuiWindow* window = g.CurrentWindow;
9985
9986
    g.GroupStack.resize(g.GroupStack.Size + 1);
9987
    ImGuiGroupData& group_data = g.GroupStack.back();
9988
    group_data.WindowID = window->ID;
9989
    group_data.BackupCursorPos = window->DC.CursorPos;
9990
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
9991
    group_data.BackupIndent = window->DC.Indent;
9992
    group_data.BackupGroupOffset = window->DC.GroupOffset;
9993
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
9994
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
9995
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
9996
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
9997
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
9998
    group_data.EmitItem = true;
9999
10000
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10001
    window->DC.Indent = window->DC.GroupOffset;
10002
    window->DC.CursorMaxPos = window->DC.CursorPos;
10003
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10004
    if (g.LogEnabled)
10005
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10006
}
10007
10008
void ImGui::EndGroup()
10009
{
10010
    ImGuiContext& g = *GImGui;
10011
    ImGuiWindow* window = g.CurrentWindow;
10012
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10013
10014
    ImGuiGroupData& group_data = g.GroupStack.back();
10015
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10016
10017
    if (window->DC.IsSetPos)
10018
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10019
10020
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10021
10022
    window->DC.CursorPos = group_data.BackupCursorPos;
10023
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10024
    window->DC.Indent = group_data.BackupIndent;
10025
    window->DC.GroupOffset = group_data.BackupGroupOffset;
10026
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10027
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10028
    if (g.LogEnabled)
10029
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10030
10031
    if (!group_data.EmitItem)
10032
    {
10033
        g.GroupStack.pop_back();
10034
        return;
10035
    }
10036
10037
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10038
    ItemSize(group_bb.GetSize());
10039
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10040
10041
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
10042
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
10043
    // Also if you grep for LastItemId you'll notice it is only used in that context.
10044
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
10045
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10046
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10047
    if (group_contains_curr_active_id)
10048
        g.LastItemData.ID = g.ActiveId;
10049
    else if (group_contains_prev_active_id)
10050
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
10051
    g.LastItemData.Rect = group_bb;
10052
10053
    // Forward Hovered flag
10054
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10055
    if (group_contains_curr_hovered_id)
10056
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10057
10058
    // Forward Edited flag
10059
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10060
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10061
10062
    // Forward Deactivated flag
10063
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10064
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10065
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10066
10067
    g.GroupStack.pop_back();
10068
    //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
10069
}
10070
10071
10072
//-----------------------------------------------------------------------------
10073
// [SECTION] SCROLLING
10074
//-----------------------------------------------------------------------------
10075
10076
// Helper to snap on edges when aiming at an item very close to the edge,
10077
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10078
// When we refactor the scrolling API this may be configurable with a flag?
10079
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10080
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10081
{
10082
    if (target <= snap_min + snap_threshold)
10083
        return ImLerp(snap_min, target, center_ratio);
10084
    if (target >= snap_max - snap_threshold)
10085
        return ImLerp(target, snap_max, center_ratio);
10086
    return target;
10087
}
10088
10089
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10090
{
10091
    ImVec2 scroll = window->Scroll;
10092
    if (window->ScrollTarget.x < FLT_MAX)
10093
    {
10094
        float decoration_total_width = window->ScrollbarSizes.x;
10095
        float center_x_ratio = window->ScrollTargetCenterRatio.x;
10096
        float scroll_target_x = window->ScrollTarget.x;
10097
        if (window->ScrollTargetEdgeSnapDist.x > 0.0f)
10098
        {
10099
            float snap_x_min = 0.0f;
10100
            float snap_x_max = window->ScrollMax.x + window->SizeFull.x - decoration_total_width;
10101
            scroll_target_x = CalcScrollEdgeSnap(scroll_target_x, snap_x_min, snap_x_max, window->ScrollTargetEdgeSnapDist.x, center_x_ratio);
10102
        }
10103
        scroll.x = scroll_target_x - center_x_ratio * (window->SizeFull.x - decoration_total_width);
10104
    }
10105
    if (window->ScrollTarget.y < FLT_MAX)
10106
    {
10107
        float decoration_total_height = window->TitleBarHeight() + window->MenuBarHeight() + window->ScrollbarSizes.y;
10108
        float center_y_ratio = window->ScrollTargetCenterRatio.y;
10109
        float scroll_target_y = window->ScrollTarget.y;
10110
        if (window->ScrollTargetEdgeSnapDist.y > 0.0f)
10111
        {
10112
            float snap_y_min = 0.0f;
10113
            float snap_y_max = window->ScrollMax.y + window->SizeFull.y - decoration_total_height;
10114
            scroll_target_y = CalcScrollEdgeSnap(scroll_target_y, snap_y_min, snap_y_max, window->ScrollTargetEdgeSnapDist.y, center_y_ratio);
10115
        }
10116
        scroll.y = scroll_target_y - center_y_ratio * (window->SizeFull.y - decoration_total_height);
10117
    }
10118
    scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f));
10119
    scroll.y = IM_FLOOR(ImMax(scroll.y, 0.0f));
10120
    if (!window->Collapsed && !window->SkipItems)
10121
    {
10122
        scroll.x = ImMin(scroll.x, window->ScrollMax.x);
10123
        scroll.y = ImMin(scroll.y, window->ScrollMax.y);
10124
    }
10125
    return scroll;
10126
}
10127
10128
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10129
{
10130
    ImGuiContext& g = *GImGui;
10131
    ImGuiWindow* window = g.CurrentWindow;
10132
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
10133
}
10134
10135
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10136
{
10137
    ScrollToRectEx(window, item_rect, flags);
10138
}
10139
10140
// Scroll to keep newly navigated item fully into view
10141
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10142
{
10143
    ImGuiContext& g = *GImGui;
10144
    ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10145
    //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
10146
10147
    // Check that only one behavior is selected per axis
10148
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10149
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10150
10151
    // Defaults
10152
    ImGuiScrollFlags in_flags = flags;
10153
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10154
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10155
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10156
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10157
10158
    const bool fully_visible_x = item_rect.Min.x >= window_rect.Min.x && item_rect.Max.x <= window_rect.Max.x;
10159
    const bool fully_visible_y = item_rect.Min.y >= window_rect.Min.y && item_rect.Max.y <= window_rect.Max.y;
10160
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= window_rect.GetWidth();
10161
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= window_rect.GetHeight();
10162
10163
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10164
    {
10165
        if (item_rect.Min.x < window_rect.Min.x || !can_be_fully_visible_x)
10166
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
10167
        else if (item_rect.Max.x >= window_rect.Max.x)
10168
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
10169
    }
10170
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10171
    {
10172
        float target_x = can_be_fully_visible_x ? ImFloor((item_rect.Min.x + item_rect.Max.x - window->InnerRect.GetWidth()) * 0.5f) : item_rect.Min.x;
10173
        SetScrollFromPosX(window, target_x - window->Pos.x, 0.0f);
10174
    }
10175
10176
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10177
    {
10178
        if (item_rect.Min.y < window_rect.Min.y || !can_be_fully_visible_y)
10179
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
10180
        else if (item_rect.Max.y >= window_rect.Max.y)
10181
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
10182
    }
10183
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10184
    {
10185
        float target_y = can_be_fully_visible_y ? ImFloor((item_rect.Min.y + item_rect.Max.y - window->InnerRect.GetHeight()) * 0.5f) : item_rect.Min.y;
10186
        SetScrollFromPosY(window, target_y - window->Pos.y, 0.0f);
10187
    }
10188
10189
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10190
    ImVec2 delta_scroll = next_scroll - window->Scroll;
10191
10192
    // Also scroll parent window to keep us into view if necessary
10193
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10194
    {
10195
        // FIXME-SCROLL: May be an option?
10196
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10197
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10198
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10199
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10200
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
10201
    }
10202
10203
    return delta_scroll;
10204
}
10205
10206
float ImGui::GetScrollX()
10207
{
10208
    ImGuiWindow* window = GImGui->CurrentWindow;
10209
    return window->Scroll.x;
10210
}
10211
10212
float ImGui::GetScrollY()
10213
{
10214
    ImGuiWindow* window = GImGui->CurrentWindow;
10215
    return window->Scroll.y;
10216
}
10217
10218
float ImGui::GetScrollMaxX()
10219
{
10220
    ImGuiWindow* window = GImGui->CurrentWindow;
10221
    return window->ScrollMax.x;
10222
}
10223
10224
float ImGui::GetScrollMaxY()
10225
{
10226
    ImGuiWindow* window = GImGui->CurrentWindow;
10227
    return window->ScrollMax.y;
10228
}
10229
10230
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10231
{
10232
    window->ScrollTarget.x = scroll_x;
10233
    window->ScrollTargetCenterRatio.x = 0.0f;
10234
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10235
}
10236
10237
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10238
{
10239
    window->ScrollTarget.y = scroll_y;
10240
    window->ScrollTargetCenterRatio.y = 0.0f;
10241
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10242
}
10243
10244
void ImGui::SetScrollX(float scroll_x)
10245
{
10246
    ImGuiContext& g = *GImGui;
10247
    SetScrollX(g.CurrentWindow, scroll_x);
10248
}
10249
10250
void ImGui::SetScrollY(float scroll_y)
10251
{
10252
    ImGuiContext& g = *GImGui;
10253
    SetScrollY(g.CurrentWindow, scroll_y);
10254
}
10255
10256
// Note that a local position will vary depending on initial scroll value,
10257
// This is a little bit confusing so bear with us:
10258
//  - local_pos = (absolution_pos - window->Pos)
10259
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10260
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10261
//  - They mostly exist because of legacy API.
10262
// Following the rules above, when trying to work with scrolling code, consider that:
10263
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10264
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10265
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
10266
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10267
{
10268
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10269
    window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); // Convert local position to scroll offset
10270
    window->ScrollTargetCenterRatio.x = center_x_ratio;
10271
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10272
}
10273
10274
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10275
{
10276
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10277
    const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect;
10278
    local_y -= decoration_up_height;
10279
    window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); // Convert local position to scroll offset
10280
    window->ScrollTargetCenterRatio.y = center_y_ratio;
10281
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10282
}
10283
10284
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10285
{
10286
    ImGuiContext& g = *GImGui;
10287
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
10288
}
10289
10290
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10291
{
10292
    ImGuiContext& g = *GImGui;
10293
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
10294
}
10295
10296
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10297
void ImGui::SetScrollHereX(float center_x_ratio)
10298
{
10299
    ImGuiContext& g = *GImGui;
10300
    ImGuiWindow* window = g.CurrentWindow;
10301
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
10302
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
10303
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10304
10305
    // Tweak: snap on edges when aiming at an item very close to the edge
10306
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
10307
}
10308
10309
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10310
void ImGui::SetScrollHereY(float center_y_ratio)
10311
{
10312
    ImGuiContext& g = *GImGui;
10313
    ImGuiWindow* window = g.CurrentWindow;
10314
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
10315
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
10316
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10317
10318
    // Tweak: snap on edges when aiming at an item very close to the edge
10319
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
10320
}
10321
10322
//-----------------------------------------------------------------------------
10323
// [SECTION] TOOLTIPS
10324
//-----------------------------------------------------------------------------
10325
10326
void ImGui::BeginTooltip()
10327
{
10328
    BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10329
}
10330
10331
void ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
10332
{
10333
    ImGuiContext& g = *GImGui;
10334
10335
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
10336
    {
10337
        // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
10338
        // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
10339
        // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
10340
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
10341
        ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
10342
        SetNextWindowPos(tooltip_pos);
10343
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
10344
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
10345
        tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
10346
    }
10347
10348
    char window_name[16];
10349
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
10350
    if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
10351
        if (ImGuiWindow* window = FindWindowByName(window_name))
10352
            if (window->Active)
10353
            {
10354
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
10355
                window->Hidden = true;
10356
                window->HiddenFramesCanSkipItems = 1; // FIXME: This may not be necessary?
10357
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
10358
            }
10359
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
10360
    Begin(window_name, NULL, flags | extra_window_flags);
10361
}
10362
10363
void ImGui::EndTooltip()
10364
{
10365
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
10366
    End();
10367
}
10368
10369
void ImGui::SetTooltipV(const char* fmt, va_list args)
10370
{
10371
    BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None);
10372
    TextV(fmt, args);
10373
    EndTooltip();
10374
}
10375
10376
void ImGui::SetTooltip(const char* fmt, ...)
10377
{
10378
    va_list args;
10379
    va_start(args, fmt);
10380
    SetTooltipV(fmt, args);
10381
    va_end(args);
10382
}
10383
10384
//-----------------------------------------------------------------------------
10385
// [SECTION] POPUPS
10386
//-----------------------------------------------------------------------------
10387
10388
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
10389
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
10390
{
10391
    ImGuiContext& g = *GImGui;
10392
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
10393
    {
10394
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
10395
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
10396
        IM_ASSERT(id == 0);
10397
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10398
            return g.OpenPopupStack.Size > 0;
10399
        else
10400
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
10401
    }
10402
    else
10403
    {
10404
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10405
        {
10406
            // Return true if the popup is open anywhere in the popup stack
10407
            for (int n = 0; n < g.OpenPopupStack.Size; n++)
10408
                if (g.OpenPopupStack[n].PopupId == id)
10409
                    return true;
10410
            return false;
10411
        }
10412
        else
10413
        {
10414
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
10415
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
10416
        }
10417
    }
10418
}
10419
10420
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
10421
{
10422
    ImGuiContext& g = *GImGui;
10423
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
10424
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
10425
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
10426
    return IsPopupOpen(id, popup_flags);
10427
}
10428
10429
ImGuiWindow* ImGui::GetTopMostPopupModal()
10430
{
10431
    ImGuiContext& g = *GImGui;
10432
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10433
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10434
            if (popup->Flags & ImGuiWindowFlags_Modal)
10435
                return popup;
10436
    return NULL;
10437
}
10438
10439
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
10440
{
10441
    ImGuiContext& g = *GImGui;
10442
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10443
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10444
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
10445
                return popup;
10446
    return NULL;
10447
}
10448
10449
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
10450
{
10451
    ImGuiContext& g = *GImGui;
10452
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10453
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X\n", str_id, id);
10454
    OpenPopupEx(id, popup_flags);
10455
}
10456
10457
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
10458
{
10459
    OpenPopupEx(id, popup_flags);
10460
}
10461
10462
// Mark popup as open (toggle toward open state).
10463
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
10464
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
10465
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
10466
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
10467
{
10468
    ImGuiContext& g = *GImGui;
10469
    ImGuiWindow* parent_window = g.CurrentWindow;
10470
    const int current_stack_size = g.BeginPopupStack.Size;
10471
10472
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
10473
        if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId))
10474
            return;
10475
10476
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
10477
    popup_ref.PopupId = id;
10478
    popup_ref.Window = NULL;
10479
    popup_ref.BackupNavWindow = g.NavWindow;            // When popup closes focus may be restored to NavWindow (depend on window type).
10480
    popup_ref.OpenFrameCount = g.FrameCount;
10481
    popup_ref.OpenParentId = parent_window->IDStack.back();
10482
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
10483
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
10484
10485
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
10486
    if (g.OpenPopupStack.Size < current_stack_size + 1)
10487
    {
10488
        g.OpenPopupStack.push_back(popup_ref);
10489
    }
10490
    else
10491
    {
10492
        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
10493
        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
10494
        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
10495
        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
10496
        {
10497
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
10498
        }
10499
        else
10500
        {
10501
            // Close child popups if any, then flag popup for open/reopen
10502
            ClosePopupToLevel(current_stack_size, false);
10503
            g.OpenPopupStack.push_back(popup_ref);
10504
        }
10505
10506
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
10507
        // This is equivalent to what ClosePopupToLevel() does.
10508
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
10509
        //    FocusWindow(parent_window);
10510
    }
10511
}
10512
10513
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
10514
// This function closes any popups that are over 'ref_window'.
10515
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
10516
{
10517
    ImGuiContext& g = *GImGui;
10518
    if (g.OpenPopupStack.Size == 0)
10519
        return;
10520
10521
    // Don't close our own child popup windows.
10522
    int popup_count_to_keep = 0;
10523
    if (ref_window)
10524
    {
10525
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
10526
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
10527
        {
10528
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
10529
            if (!popup.Window)
10530
                continue;
10531
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
10532
            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
10533
                continue;
10534
10535
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
10536
            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
10537
            //     Window -> Popup1 -> Popup2 -> Popup3
10538
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
10539
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
10540
            bool ref_window_is_descendent_of_popup = false;
10541
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
10542
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
10543
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
10544
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
10545
                    {
10546
                        ref_window_is_descendent_of_popup = true;
10547
                        break;
10548
                    }
10549
            if (!ref_window_is_descendent_of_popup)
10550
                break;
10551
        }
10552
    }
10553
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10554
    {
10555
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
10556
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
10557
    }
10558
}
10559
10560
void ImGui::ClosePopupsExceptModals()
10561
{
10562
    ImGuiContext& g = *GImGui;
10563
10564
    int popup_count_to_keep;
10565
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
10566
    {
10567
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
10568
        if (!window || window->Flags & ImGuiWindowFlags_Modal)
10569
            break;
10570
    }
10571
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10572
        ClosePopupToLevel(popup_count_to_keep, true);
10573
}
10574
10575
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
10576
{
10577
    ImGuiContext& g = *GImGui;
10578
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
10579
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
10580
10581
    // Trim open popup stack
10582
    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
10583
    ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
10584
    g.OpenPopupStack.resize(remaining);
10585
10586
    if (restore_focus_to_window_under_popup)
10587
    {
10588
        ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
10589
        if (focus_window && !focus_window->WasActive && popup_window)
10590
        {
10591
            // Fallback
10592
            FocusTopMostWindowUnderOne(popup_window, NULL);
10593
        }
10594
        else
10595
        {
10596
            if (g.NavLayer == ImGuiNavLayer_Main && focus_window)
10597
                focus_window = NavRestoreLastChildNavWindow(focus_window);
10598
            FocusWindow(focus_window);
10599
        }
10600
    }
10601
}
10602
10603
// Close the popup we have begin-ed into.
10604
void ImGui::CloseCurrentPopup()
10605
{
10606
    ImGuiContext& g = *GImGui;
10607
    int popup_idx = g.BeginPopupStack.Size - 1;
10608
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
10609
        return;
10610
10611
    // Closing a menu closes its top-most parent popup (unless a modal)
10612
    while (popup_idx > 0)
10613
    {
10614
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
10615
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
10616
        bool close_parent = false;
10617
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
10618
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
10619
                close_parent = true;
10620
        if (!close_parent)
10621
            break;
10622
        popup_idx--;
10623
    }
10624
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
10625
    ClosePopupToLevel(popup_idx, true);
10626
10627
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
10628
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
10629
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
10630
    if (ImGuiWindow* window = g.NavWindow)
10631
        window->DC.NavHideHighlightOneFrame = true;
10632
}
10633
10634
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
10635
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
10636
{
10637
    ImGuiContext& g = *GImGui;
10638
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
10639
    {
10640
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10641
        return false;
10642
    }
10643
10644
    char name[20];
10645
    if (flags & ImGuiWindowFlags_ChildMenu)
10646
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
10647
    else
10648
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
10649
10650
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
10651
    bool is_open = Begin(name, NULL, flags);
10652
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
10653
        EndPopup();
10654
10655
    return is_open;
10656
}
10657
10658
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
10659
{
10660
    ImGuiContext& g = *GImGui;
10661
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
10662
    {
10663
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10664
        return false;
10665
    }
10666
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
10667
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10668
    return BeginPopupEx(id, flags);
10669
}
10670
10671
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
10672
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
10673
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
10674
{
10675
    ImGuiContext& g = *GImGui;
10676
    ImGuiWindow* window = g.CurrentWindow;
10677
    const ImGuiID id = window->GetID(name);
10678
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
10679
    {
10680
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10681
        return false;
10682
    }
10683
10684
    // Center modal windows by default for increased visibility
10685
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
10686
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
10687
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
10688
    {
10689
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
10690
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
10691
    }
10692
10693
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
10694
    const bool is_open = Begin(name, p_open, flags);
10695
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
10696
    {
10697
        EndPopup();
10698
        if (is_open)
10699
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
10700
        return false;
10701
    }
10702
    return is_open;
10703
}
10704
10705
void ImGui::EndPopup()
10706
{
10707
    ImGuiContext& g = *GImGui;
10708
    ImGuiWindow* window = g.CurrentWindow;
10709
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
10710
    IM_ASSERT(g.BeginPopupStack.Size > 0);
10711
10712
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
10713
    if (g.NavWindow == window)
10714
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
10715
10716
    // Child-popups don't need to be laid out
10717
    IM_ASSERT(g.WithinEndChild == false);
10718
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
10719
        g.WithinEndChild = true;
10720
    End();
10721
    g.WithinEndChild = false;
10722
}
10723
10724
// Helper to open a popup if mouse button is released over the item
10725
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
10726
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
10727
{
10728
    ImGuiContext& g = *GImGui;
10729
    ImGuiWindow* window = g.CurrentWindow;
10730
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10731
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
10732
    {
10733
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
10734
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
10735
        OpenPopupEx(id, popup_flags);
10736
    }
10737
}
10738
10739
// This is a helper to handle the simplest case of associating one named popup to one given widget.
10740
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
10741
// - To create a popup with a specific identifier, pass it in str_id.
10742
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
10743
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
10744
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
10745
//   This is essentially the same as:
10746
//       id = str_id ? GetID(str_id) : GetItemID();
10747
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
10748
//       return BeginPopup(id);
10749
//   Which is essentially the same as:
10750
//       id = str_id ? GetID(str_id) : GetItemID();
10751
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
10752
//           OpenPopup(id);
10753
//       return BeginPopup(id);
10754
//   The main difference being that this is tweaked to avoid computing the ID twice.
10755
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
10756
{
10757
    ImGuiContext& g = *GImGui;
10758
    ImGuiWindow* window = g.CurrentWindow;
10759
    if (window->SkipItems)
10760
        return false;
10761
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
10762
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
10763
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10764
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
10765
        OpenPopupEx(id, popup_flags);
10766
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
10767
}
10768
10769
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
10770
{
10771
    ImGuiContext& g = *GImGui;
10772
    ImGuiWindow* window = g.CurrentWindow;
10773
    if (!str_id)
10774
        str_id = "window_context";
10775
    ImGuiID id = window->GetID(str_id);
10776
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10777
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
10778
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
10779
            OpenPopupEx(id, popup_flags);
10780
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
10781
}
10782
10783
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
10784
{
10785
    ImGuiContext& g = *GImGui;
10786
    ImGuiWindow* window = g.CurrentWindow;
10787
    if (!str_id)
10788
        str_id = "void_context";
10789
    ImGuiID id = window->GetID(str_id);
10790
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10791
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
10792
        if (GetTopMostPopupModal() == NULL)
10793
            OpenPopupEx(id, popup_flags);
10794
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
10795
}
10796
10797
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
10798
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
10799
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
10800
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
10801
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
10802
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
10803
{
10804
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
10805
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
10806
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
10807
10808
    // Combo Box policy (we want a connecting edge)
10809
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
10810
    {
10811
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
10812
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
10813
        {
10814
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
10815
            if (n != -1 && dir == *last_dir) // Already tried this direction?
10816
                continue;
10817
            ImVec2 pos;
10818
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
10819
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
10820
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
10821
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
10822
            if (!r_outer.Contains(ImRect(pos, pos + size)))
10823
                continue;
10824
            *last_dir = dir;
10825
            return pos;
10826
        }
10827
    }
10828
10829
    // Tooltip and Default popup policy
10830
    // (Always first try the direction we used on the last frame, if any)
10831
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
10832
    {
10833
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
10834
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
10835
        {
10836
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
10837
            if (n != -1 && dir == *last_dir) // Already tried this direction?
10838
                continue;
10839
10840
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
10841
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
10842
10843
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
10844
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
10845
                continue;
10846
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
10847
                continue;
10848
10849
            ImVec2 pos;
10850
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
10851
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
10852
10853
            // Clamp top-left corner of popup
10854
            pos.x = ImMax(pos.x, r_outer.Min.x);
10855
            pos.y = ImMax(pos.y, r_outer.Min.y);
10856
10857
            *last_dir = dir;
10858
            return pos;
10859
        }
10860
    }
10861
10862
    // Fallback when not enough room:
10863
    *last_dir = ImGuiDir_None;
10864
10865
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
10866
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
10867
        return ref_pos + ImVec2(2, 2);
10868
10869
    // Otherwise try to keep within display
10870
    ImVec2 pos = ref_pos;
10871
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
10872
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
10873
    return pos;
10874
}
10875
10876
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
10877
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
10878
{
10879
    ImGuiContext& g = *GImGui;
10880
    ImRect r_screen;
10881
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
10882
    {
10883
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
10884
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
10885
        r_screen.Min = monitor.WorkPos;
10886
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
10887
    }
10888
    else
10889
    {
10890
        // Use the full viewport area (not work area) for popups
10891
        r_screen = window->Viewport->GetMainRect();
10892
    }
10893
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
10894
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
10895
    return r_screen;
10896
}
10897
10898
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
10899
{
10900
    ImGuiContext& g = *GImGui;
10901
10902
    ImRect r_outer = GetPopupAllowedExtentRect(window);
10903
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
10904
    {
10905
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
10906
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
10907
        ImGuiWindow* parent_window = window->ParentWindow;
10908
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
10909
        ImRect r_avoid;
10910
        if (parent_window->DC.MenuBarAppending)
10911
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
10912
        else
10913
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
10914
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
10915
    }
10916
    if (window->Flags & ImGuiWindowFlags_Popup)
10917
    {
10918
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
10919
    }
10920
    if (window->Flags & ImGuiWindowFlags_Tooltip)
10921
    {
10922
        // Position tooltip (always follows mouse)
10923
        float sc = g.Style.MouseCursorScale;
10924
        ImVec2 ref_pos = NavCalcPreferredRefPos();
10925
        ImRect r_avoid;
10926
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
10927
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
10928
        else
10929
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
10930
        return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
10931
    }
10932
    IM_ASSERT(0);
10933
    return window->Pos;
10934
}
10935
10936
//-----------------------------------------------------------------------------
10937
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
10938
//-----------------------------------------------------------------------------
10939
10940
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
10941
// In our terminology those should be interchangeable, yet right now this is super confusing.
10942
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
10943
10944
void ImGui::SetNavWindow(ImGuiWindow* window)
10945
{
10946
    ImGuiContext& g = *GImGui;
10947
    if (g.NavWindow != window)
10948
    {
10949
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
10950
        g.NavWindow = window;
10951
    }
10952
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
10953
    NavUpdateAnyRequestFlag();
10954
}
10955
10956
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
10957
{
10958
    ImGuiContext& g = *GImGui;
10959
    IM_ASSERT(g.NavWindow != NULL);
10960
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
10961
    g.NavId = id;
10962
    g.NavLayer = nav_layer;
10963
    g.NavFocusScopeId = focus_scope_id;
10964
    g.NavWindow->NavLastIds[nav_layer] = id;
10965
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
10966
}
10967
10968
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
10969
{
10970
    ImGuiContext& g = *GImGui;
10971
    IM_ASSERT(id != 0);
10972
10973
    if (g.NavWindow != window)
10974
       SetNavWindow(window);
10975
10976
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
10977
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
10978
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
10979
    g.NavId = id;
10980
    g.NavLayer = nav_layer;
10981
    g.NavFocusScopeId = g.CurrentFocusScopeId;
10982
    window->NavLastIds[nav_layer] = id;
10983
    if (g.LastItemData.ID == id)
10984
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
10985
10986
    if (g.ActiveIdSource == ImGuiInputSource_Nav)
10987
        g.NavDisableMouseHover = true;
10988
    else
10989
        g.NavDisableHighlight = true;
10990
}
10991
10992
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
10993
{
10994
    if (ImFabs(dx) > ImFabs(dy))
10995
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
10996
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
10997
}
10998
10999
static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
11000
{
11001
    if (a1 < b0)
11002
        return a1 - b0;
11003
    if (b1 < a0)
11004
        return a0 - b1;
11005
    return 0.0f;
11006
}
11007
11008
static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
11009
{
11010
    if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
11011
    {
11012
        r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
11013
        r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
11014
    }
11015
    else // FIXME: PageUp/PageDown are leaving move_dir == None
11016
    {
11017
        r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
11018
        r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
11019
    }
11020
}
11021
11022
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11023
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11024
{
11025
    ImGuiContext& g = *GImGui;
11026
    ImGuiWindow* window = g.CurrentWindow;
11027
    if (g.NavLayer != window->DC.NavLayerCurrent)
11028
        return false;
11029
11030
    // FIXME: Those are not good variables names
11031
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
11032
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
11033
    g.NavScoringDebugCount++;
11034
11035
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11036
    if (window->ParentWindow == g.NavWindow)
11037
    {
11038
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
11039
        if (!window->ClipRect.Overlaps(cand))
11040
            return false;
11041
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11042
    }
11043
11044
    // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
11045
    // For example, this ensures that items in one column are not reached when moving vertically from items in another column.
11046
    NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
11047
11048
    // Compute distance between boxes
11049
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11050
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
11051
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
11052
    if (dby != 0.0f && dbx != 0.0f)
11053
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11054
    float dist_box = ImFabs(dbx) + ImFabs(dby);
11055
11056
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
11057
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11058
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11059
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11060
11061
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11062
    ImGuiDir quadrant;
11063
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11064
    if (dbx != 0.0f || dby != 0.0f)
11065
    {
11066
        // For non-overlapping boxes, use distance between boxes
11067
        dax = dbx;
11068
        day = dby;
11069
        dist_axial = dist_box;
11070
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
11071
    }
11072
    else if (dcx != 0.0f || dcy != 0.0f)
11073
    {
11074
        // For overlapping boxes with different centers, use distance between centers
11075
        dax = dcx;
11076
        day = dcy;
11077
        dist_axial = dist_center;
11078
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
11079
    }
11080
    else
11081
    {
11082
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
11083
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11084
    }
11085
11086
#if IMGUI_DEBUG_NAV_SCORING
11087
    char buf[128];
11088
    if (IsMouseHoveringRect(cand.Min, cand.Max))
11089
    {
11090
        ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
11091
        ImDrawList* draw_list = GetForegroundDrawList(window);
11092
        draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
11093
        draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
11094
        draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));
11095
        draw_list->AddText(cand.Max, ~0U, buf);
11096
    }
11097
    else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
11098
    {
11099
        if (quadrant == g.NavMoveDir)
11100
        {
11101
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11102
            ImDrawList* draw_list = GetForegroundDrawList(window);
11103
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
11104
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11105
        }
11106
    }
11107
#endif
11108
11109
    // Is it in the quadrant we're interested in moving to?
11110
    bool new_best = false;
11111
    const ImGuiDir move_dir = g.NavMoveDir;
11112
    if (quadrant == move_dir)
11113
    {
11114
        // Does it beat the current best candidate?
11115
        if (dist_box < result->DistBox)
11116
        {
11117
            result->DistBox = dist_box;
11118
            result->DistCenter = dist_center;
11119
            return true;
11120
        }
11121
        if (dist_box == result->DistBox)
11122
        {
11123
            // Try using distance between center points to break ties
11124
            if (dist_center < result->DistCenter)
11125
            {
11126
                result->DistCenter = dist_center;
11127
                new_best = true;
11128
            }
11129
            else if (dist_center == result->DistCenter)
11130
            {
11131
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11132
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
11133
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
11134
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11135
                    new_best = true;
11136
            }
11137
        }
11138
    }
11139
11140
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
11141
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11142
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
11143
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
11144
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11145
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
11146
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11147
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
11148
            {
11149
                result->DistAxial = dist_axial;
11150
                new_best = true;
11151
            }
11152
11153
    return new_best;
11154
}
11155
11156
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11157
{
11158
    ImGuiContext& g = *GImGui;
11159
    ImGuiWindow* window = g.CurrentWindow;
11160
    result->Window = window;
11161
    result->ID = g.LastItemData.ID;
11162
    result->FocusScopeId = g.CurrentFocusScopeId;
11163
    result->InFlags = g.LastItemData.InFlags;
11164
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11165
}
11166
11167
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11168
// This is called after LastItemData is set.
11169
static void ImGui::NavProcessItem()
11170
{
11171
    ImGuiContext& g = *GImGui;
11172
    ImGuiWindow* window = g.CurrentWindow;
11173
    const ImGuiID id = g.LastItemData.ID;
11174
    const ImRect nav_bb = g.LastItemData.NavRect;
11175
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11176
11177
    // Process Init Request
11178
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11179
    {
11180
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11181
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11182
        if (candidate_for_nav_default_focus || g.NavInitResultId == 0)
11183
        {
11184
            g.NavInitResultId = id;
11185
            g.NavInitResultRectRel = WindowRectAbsToRel(window, nav_bb);
11186
        }
11187
        if (candidate_for_nav_default_focus)
11188
        {
11189
            g.NavInitRequest = false; // Found a match, clear request
11190
            NavUpdateAnyRequestFlag();
11191
        }
11192
    }
11193
11194
    // Process Move Request (scoring for navigation)
11195
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11196
    if (g.NavMoveScoringItems)
11197
    {
11198
        const bool is_tab_stop = (item_flags & ImGuiItemFlags_Inputable) && (item_flags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
11199
        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) != 0;
11200
        if (is_tabbing)
11201
        {
11202
            if (is_tab_stop || (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi))
11203
                NavProcessItemForTabbingRequest(id);
11204
        }
11205
        else if ((g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & ImGuiItemFlags_Disabled))
11206
        {
11207
            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11208
            if (!is_tabbing)
11209
            {
11210
                if (NavScoreItem(result))
11211
                    NavApplyItemToResult(result);
11212
11213
                // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11214
                const float VISIBLE_RATIO = 0.70f;
11215
                if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
11216
                    if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
11217
                        if (NavScoreItem(&g.NavMoveResultLocalVisible))
11218
                            NavApplyItemToResult(&g.NavMoveResultLocalVisible);
11219
            }
11220
        }
11221
    }
11222
11223
    // Update window-relative bounding box of navigated item
11224
    if (g.NavId == id)
11225
    {
11226
        if (g.NavWindow != window)
11227
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11228
        g.NavLayer = window->DC.NavLayerCurrent;
11229
        g.NavFocusScopeId = g.CurrentFocusScopeId;
11230
        g.NavIdIsAlive = true;
11231
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb);    // Store item bounding box (relative to window position)
11232
    }
11233
}
11234
11235
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11236
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11237
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
11238
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
11239
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
11240
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
11241
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
11242
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id)
11243
{
11244
    ImGuiContext& g = *GImGui;
11245
11246
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11247
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
11248
    if (g.NavTabbingDir == +1)
11249
    {
11250
        // Tab Forward or SetKeyboardFocusHere() with >= 0
11251
        if (g.NavTabbingResultFirst.ID == 0)
11252
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11253
        if (--g.NavTabbingCounter == 0)
11254
            NavMoveRequestResolveWithLastItem(result);
11255
        else if (g.NavId == id)
11256
            g.NavTabbingCounter = 1;
11257
    }
11258
    else if (g.NavTabbingDir == -1)
11259
    {
11260
        // Tab Backward
11261
        if (g.NavId == id)
11262
        {
11263
            if (result->ID)
11264
            {
11265
                g.NavMoveScoringItems = false;
11266
                NavUpdateAnyRequestFlag();
11267
            }
11268
        }
11269
        else
11270
        {
11271
            NavApplyItemToResult(result);
11272
        }
11273
    }
11274
    else if (g.NavTabbingDir == 0)
11275
    {
11276
        // Tab Init
11277
        if (g.NavTabbingResultFirst.ID == 0)
11278
            NavMoveRequestResolveWithLastItem(&g.NavTabbingResultFirst);
11279
    }
11280
}
11281
11282
bool ImGui::NavMoveRequestButNoResultYet()
11283
{
11284
    ImGuiContext& g = *GImGui;
11285
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
11286
}
11287
11288
// FIXME: ScoringRect is not set
11289
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11290
{
11291
    ImGuiContext& g = *GImGui;
11292
    IM_ASSERT(g.NavWindow != NULL);
11293
11294
    if (move_flags & ImGuiNavMoveFlags_Tabbing)
11295
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
11296
11297
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
11298
    g.NavMoveDir = move_dir;
11299
    g.NavMoveDirForDebug = move_dir;
11300
    g.NavMoveClipDir = clip_dir;
11301
    g.NavMoveFlags = move_flags;
11302
    g.NavMoveScrollFlags = scroll_flags;
11303
    g.NavMoveForwardToNextFrame = false;
11304
    g.NavMoveKeyMods = g.IO.KeyMods;
11305
    g.NavMoveResultLocal.Clear();
11306
    g.NavMoveResultLocalVisible.Clear();
11307
    g.NavMoveResultOther.Clear();
11308
    g.NavTabbingCounter = 0;
11309
    g.NavTabbingResultFirst.Clear();
11310
    NavUpdateAnyRequestFlag();
11311
}
11312
11313
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
11314
{
11315
    ImGuiContext& g = *GImGui;
11316
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
11317
    NavApplyItemToResult(result);
11318
    NavUpdateAnyRequestFlag();
11319
}
11320
11321
void ImGui::NavMoveRequestCancel()
11322
{
11323
    ImGuiContext& g = *GImGui;
11324
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11325
    NavUpdateAnyRequestFlag();
11326
}
11327
11328
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
11329
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11330
{
11331
    ImGuiContext& g = *GImGui;
11332
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
11333
    NavMoveRequestCancel();
11334
    g.NavMoveForwardToNextFrame = true;
11335
    g.NavMoveDir = move_dir;
11336
    g.NavMoveClipDir = clip_dir;
11337
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
11338
    g.NavMoveScrollFlags = scroll_flags;
11339
}
11340
11341
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
11342
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
11343
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
11344
{
11345
    ImGuiContext& g = *GImGui;
11346
    IM_ASSERT(wrap_flags != 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
11347
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it, NavEndFrame() will do the same test
11348
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
11349
        g.NavMoveFlags |= wrap_flags;
11350
}
11351
11352
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
11353
// This way we could find the last focused window among our children. It would be much less confusing this way?
11354
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
11355
{
11356
    ImGuiWindow* parent = nav_window;
11357
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
11358
        parent = parent->ParentWindow;
11359
    if (parent && parent != nav_window)
11360
        parent->NavLastChildNavWindow = nav_window;
11361
}
11362
11363
// Restore the last focused child.
11364
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
11365
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
11366
{
11367
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
11368
        return window->NavLastChildNavWindow;
11369
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
11370
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
11371
            return tab->Window;
11372
    return window;
11373
}
11374
11375
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
11376
{
11377
    ImGuiContext& g = *GImGui;
11378
    if (layer == ImGuiNavLayer_Main)
11379
    {
11380
        ImGuiWindow* prev_nav_window = g.NavWindow;
11381
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
11382
        if (prev_nav_window)
11383
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
11384
    }
11385
    ImGuiWindow* window = g.NavWindow;
11386
    if (window->NavLastIds[layer] != 0)
11387
    {
11388
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
11389
    }
11390
    else
11391
    {
11392
        g.NavLayer = layer;
11393
        NavInitWindow(window, true);
11394
    }
11395
}
11396
11397
void ImGui::NavRestoreHighlightAfterMove()
11398
{
11399
    ImGuiContext& g = *GImGui;
11400
    g.NavDisableHighlight = false;
11401
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
11402
}
11403
11404
static inline void ImGui::NavUpdateAnyRequestFlag()
11405
{
11406
    ImGuiContext& g = *GImGui;
11407
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
11408
    if (g.NavAnyRequest)
11409
        IM_ASSERT(g.NavWindow != NULL);
11410
}
11411
11412
// This needs to be called before we submit any widget (aka in or before Begin)
11413
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
11414
{
11415
    // FIXME: ChildWindow test here is wrong for docking
11416
    ImGuiContext& g = *GImGui;
11417
    IM_ASSERT(window == g.NavWindow);
11418
11419
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
11420
    {
11421
        g.NavId = 0;
11422
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11423
        return;
11424
    }
11425
11426
    bool init_for_nav = false;
11427
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
11428
        init_for_nav = true;
11429
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
11430
    if (init_for_nav)
11431
    {
11432
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
11433
        g.NavInitRequest = true;
11434
        g.NavInitRequestFromMove = false;
11435
        g.NavInitResultId = 0;
11436
        g.NavInitResultRectRel = ImRect();
11437
        NavUpdateAnyRequestFlag();
11438
    }
11439
    else
11440
    {
11441
        g.NavId = window->NavLastIds[0];
11442
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11443
    }
11444
}
11445
11446
static ImVec2 ImGui::NavCalcPreferredRefPos()
11447
{
11448
    ImGuiContext& g = *GImGui;
11449
    ImGuiWindow* window = g.NavWindow;
11450
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
11451
    {
11452
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
11453
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
11454
        // In theory we could move that +1.0f offset in OpenPopupEx()
11455
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
11456
        return ImVec2(p.x + 1.0f, p.y);
11457
    }
11458
    else
11459
    {
11460
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
11461
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
11462
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
11463
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
11464
        {
11465
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11466
            rect_rel.Translate(window->Scroll - next_scroll);
11467
        }
11468
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
11469
        ImGuiViewport* viewport = window->Viewport;
11470
        return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
11471
    }
11472
}
11473
11474
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
11475
{
11476
    ImGuiContext& g = *GImGui;
11477
    float repeat_delay, repeat_rate;
11478
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
11479
11480
    ImGuiKey key_less, key_more;
11481
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
11482
    {
11483
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
11484
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
11485
    }
11486
    else
11487
    {
11488
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
11489
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
11490
    }
11491
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
11492
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
11493
        amount = 0.0f;
11494
    return amount;
11495
}
11496
11497
static void ImGui::NavUpdate()
11498
{
11499
    ImGuiContext& g = *GImGui;
11500
    ImGuiIO& io = g.IO;
11501
11502
    io.WantSetMousePos = false;
11503
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
11504
11505
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
11506
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
11507
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11508
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
11509
    if (nav_gamepad_active)
11510
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
11511
            if (IsKeyDown(key))
11512
                g.NavInputSource = ImGuiInputSource_Gamepad;
11513
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11514
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
11515
    if (nav_keyboard_active)
11516
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
11517
            if (IsKeyDown(key))
11518
                g.NavInputSource = ImGuiInputSource_Keyboard;
11519
11520
    // Process navigation init request (select first/default focus)
11521
    if (g.NavInitResultId != 0)
11522
        NavInitRequestApplyResult();
11523
    g.NavInitRequest = false;
11524
    g.NavInitRequestFromMove = false;
11525
    g.NavInitResultId = 0;
11526
    g.NavJustMovedToId = 0;
11527
11528
    // Process navigation move request
11529
    if (g.NavMoveSubmitted)
11530
        NavMoveRequestApplyResult();
11531
    g.NavTabbingCounter = 0;
11532
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11533
11534
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
11535
    bool set_mouse_pos = false;
11536
    if (g.NavMousePosDirty && g.NavIdIsAlive)
11537
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
11538
            set_mouse_pos = true;
11539
    g.NavMousePosDirty = false;
11540
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
11541
11542
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
11543
    if (g.NavWindow)
11544
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
11545
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
11546
        g.NavWindow->NavLastChildNavWindow = NULL;
11547
11548
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
11549
    NavUpdateWindowing();
11550
11551
    // Set output flags for user application
11552
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
11553
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
11554
11555
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
11556
    NavUpdateCancelRequest();
11557
11558
    // Process manual activation request
11559
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavActivateInputId = 0;
11560
    g.NavActivateFlags = ImGuiActivateFlags_None;
11561
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11562
    {
11563
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
11564
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
11565
        const bool input_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Enter)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
11566
        const bool input_pressed = input_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Enter, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
11567
        if (g.ActiveId == 0 && activate_pressed)
11568
        {
11569
            g.NavActivateId = g.NavId;
11570
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
11571
        }
11572
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
11573
        {
11574
            g.NavActivateInputId = g.NavId;
11575
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
11576
        }
11577
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
11578
            g.NavActivateDownId = g.NavId;
11579
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
11580
            g.NavActivatePressedId = g.NavId;
11581
    }
11582
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11583
        g.NavDisableHighlight = true;
11584
    if (g.NavActivateId != 0)
11585
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
11586
11587
    // Process programmatic activation request
11588
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
11589
    if (g.NavNextActivateId != 0)
11590
    {
11591
        if (g.NavNextActivateFlags & ImGuiActivateFlags_PreferInput)
11592
            g.NavActivateInputId = g.NavNextActivateId;
11593
        else
11594
            g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
11595
        g.NavActivateFlags = g.NavNextActivateFlags;
11596
    }
11597
    g.NavNextActivateId = 0;
11598
11599
    // Process move requests
11600
    NavUpdateCreateMoveRequest();
11601
    if (g.NavMoveDir == ImGuiDir_None)
11602
        NavUpdateCreateTabbingRequest();
11603
    NavUpdateAnyRequestFlag();
11604
    g.NavIdIsAlive = false;
11605
11606
    // Scrolling
11607
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
11608
    {
11609
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
11610
        ImGuiWindow* window = g.NavWindow;
11611
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
11612
        const ImGuiDir move_dir = g.NavMoveDir;
11613
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll && move_dir != ImGuiDir_None)
11614
        {
11615
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
11616
                SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
11617
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
11618
                SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
11619
        }
11620
11621
        // *Normal* Manual scroll with LStick
11622
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
11623
        if (nav_gamepad_active)
11624
        {
11625
            const ImVec2 scroll_dir = GetKeyVector2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
11626
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
11627
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
11628
                SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
11629
            if (scroll_dir.y != 0.0f)
11630
                SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
11631
        }
11632
    }
11633
11634
    // Always prioritize mouse highlight if navigation is disabled
11635
    if (!nav_keyboard_active && !nav_gamepad_active)
11636
    {
11637
        g.NavDisableHighlight = true;
11638
        g.NavDisableMouseHover = set_mouse_pos = false;
11639
    }
11640
11641
    // Update mouse position if requested
11642
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
11643
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
11644
    {
11645
        io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
11646
        io.WantSetMousePos = true;
11647
        //IMGUI_DEBUG_LOG_IO("SetMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
11648
    }
11649
11650
    // [DEBUG]
11651
    g.NavScoringDebugCount = 0;
11652
#if IMGUI_DEBUG_NAV_RECTS
11653
    if (g.NavWindow)
11654
    {
11655
        ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
11656
        if (1) { for (int layer = 0; layer < 2; layer++) { ImRect r = WindowRectRelToAbs(g.NavWindow, g.NavWindow->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255,200,0,255)); } } // [DEBUG]
11657
        if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
11658
    }
11659
#endif
11660
}
11661
11662
void ImGui::NavInitRequestApplyResult()
11663
{
11664
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
11665
    ImGuiContext& g = *GImGui;
11666
    if (!g.NavWindow)
11667
        return;
11668
11669
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
11670
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
11671
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
11672
    SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
11673
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
11674
    if (g.NavInitRequestFromMove)
11675
        NavRestoreHighlightAfterMove();
11676
}
11677
11678
void ImGui::NavUpdateCreateMoveRequest()
11679
{
11680
    ImGuiContext& g = *GImGui;
11681
    ImGuiIO& io = g.IO;
11682
    ImGuiWindow* window = g.NavWindow;
11683
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11684
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11685
11686
    if (g.NavMoveForwardToNextFrame && window != NULL)
11687
    {
11688
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
11689
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
11690
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
11691
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
11692
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
11693
    }
11694
    else
11695
    {
11696
        // Initiate directional inputs request
11697
        g.NavMoveDir = ImGuiDir_None;
11698
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
11699
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
11700
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
11701
        {
11702
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | ImGuiInputFlags_RepeatRateNavMove;
11703
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
11704
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
11705
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
11706
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
11707
        }
11708
        g.NavMoveClipDir = g.NavMoveDir;
11709
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
11710
    }
11711
11712
    // Update PageUp/PageDown/Home/End scroll
11713
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
11714
    float scoring_rect_offset_y = 0.0f;
11715
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
11716
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
11717
    if (scoring_rect_offset_y != 0.0f)
11718
    {
11719
        g.NavScoringNoClipRect = window->InnerRect;
11720
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
11721
    }
11722
11723
    // [DEBUG] Always send a request
11724
#if IMGUI_DEBUG_NAV_SCORING
11725
    if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
11726
        g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
11727
    if (io.KeyCtrl && g.NavMoveDir == ImGuiDir_None)
11728
    {
11729
        g.NavMoveDir = g.NavMoveDirForDebug;
11730
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
11731
    }
11732
#endif
11733
11734
    // Submit
11735
    g.NavMoveForwardToNextFrame = false;
11736
    if (g.NavMoveDir != ImGuiDir_None)
11737
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
11738
11739
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
11740
    if (g.NavMoveSubmitted && g.NavId == 0)
11741
    {
11742
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
11743
        g.NavInitRequest = g.NavInitRequestFromMove = true;
11744
        g.NavInitResultId = 0;
11745
        g.NavDisableHighlight = false;
11746
    }
11747
11748
    // When using gamepad, we project the reference nav bounding box into window visible area.
11749
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad all movements are relative
11750
    // (can't focus a visible object like we can with the mouse).
11751
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
11752
    {
11753
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
11754
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
11755
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
11756
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
11757
        {
11758
            //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
11759
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
11760
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
11761
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
11762
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
11763
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
11764
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
11765
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
11766
            g.NavId = 0;
11767
        }
11768
    }
11769
11770
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
11771
    ImRect scoring_rect;
11772
    if (window != NULL)
11773
    {
11774
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
11775
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
11776
        scoring_rect.TranslateY(scoring_rect_offset_y);
11777
        scoring_rect.Min.x = ImMin(scoring_rect.Min.x + 1.0f, scoring_rect.Max.x);
11778
        scoring_rect.Max.x = scoring_rect.Min.x;
11779
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
11780
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
11781
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
11782
    }
11783
    g.NavScoringRect = scoring_rect;
11784
    g.NavScoringNoClipRect.Add(scoring_rect);
11785
}
11786
11787
void ImGui::NavUpdateCreateTabbingRequest()
11788
{
11789
    ImGuiContext& g = *GImGui;
11790
    ImGuiWindow* window = g.NavWindow;
11791
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
11792
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
11793
        return;
11794
11795
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
11796
    if (!tab_pressed)
11797
        return;
11798
11799
    // Initiate tabbing request
11800
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
11801
    // Initially this was designed to use counters and modulo arithmetic, but that could not work with unsubmitted items (list clipper). Instead we use a strategy close to other move requests.
11802
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
11803
    //// FIXME: We use (g.ActiveId == 0) but (g.NavDisableHighlight == false) might be righter once we can tab through anything
11804
    g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
11805
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
11806
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
11807
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, ImGuiNavMoveFlags_Tabbing, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
11808
    g.NavTabbingCounter = -1;
11809
}
11810
11811
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
11812
void ImGui::NavMoveRequestApplyResult()
11813
{
11814
    ImGuiContext& g = *GImGui;
11815
#if IMGUI_DEBUG_NAV_SCORING
11816
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
11817
        return;
11818
#endif
11819
11820
    // Select which result to use
11821
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
11822
11823
    // Tabbing forward wrap
11824
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
11825
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
11826
            result = &g.NavTabbingResultFirst;
11827
11828
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
11829
    if (result == NULL)
11830
    {
11831
        if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
11832
            g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
11833
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
11834
            NavRestoreHighlightAfterMove();
11835
        return;
11836
    }
11837
11838
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
11839
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
11840
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
11841
            result = &g.NavMoveResultLocalVisible;
11842
11843
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
11844
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
11845
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
11846
            result = &g.NavMoveResultOther;
11847
    IM_ASSERT(g.NavWindow && result->Window);
11848
11849
    // Scroll to keep newly navigated item fully into view.
11850
    if (g.NavLayer == ImGuiNavLayer_Main)
11851
    {
11852
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
11853
        {
11854
            // FIXME: Should remove this
11855
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
11856
            SetScrollY(result->Window, scroll_target);
11857
        }
11858
        else
11859
        {
11860
            ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
11861
            ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
11862
        }
11863
    }
11864
11865
    if (g.NavWindow != result->Window)
11866
    {
11867
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
11868
        g.NavWindow = result->Window;
11869
    }
11870
    if (g.ActiveId != result->ID)
11871
        ClearActiveID();
11872
    if (g.NavId != result->ID)
11873
    {
11874
        // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
11875
        g.NavJustMovedToId = result->ID;
11876
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
11877
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
11878
    }
11879
11880
    // Focus
11881
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
11882
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
11883
11884
    // Tabbing: Activates Inputable or Focus non-Inputable
11885
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable))
11886
    {
11887
        g.NavNextActivateId = result->ID;
11888
        g.NavNextActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
11889
        g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
11890
    }
11891
11892
    // Activate
11893
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
11894
    {
11895
        g.NavNextActivateId = result->ID;
11896
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
11897
    }
11898
11899
    // Enable nav highlight
11900
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
11901
        NavRestoreHighlightAfterMove();
11902
}
11903
11904
// Process NavCancel input (to close a popup, get back to parent, clear focus)
11905
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
11906
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
11907
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
11908
static void ImGui::NavUpdateCancelRequest()
11909
{
11910
    ImGuiContext& g = *GImGui;
11911
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11912
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11913
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
11914
        return;
11915
11916
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
11917
    if (g.ActiveId != 0)
11918
    {
11919
        ClearActiveID();
11920
    }
11921
    else if (g.NavLayer != ImGuiNavLayer_Main)
11922
    {
11923
        // Leave the "menu" layer
11924
        NavRestoreLayer(ImGuiNavLayer_Main);
11925
        NavRestoreHighlightAfterMove();
11926
    }
11927
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
11928
    {
11929
        // Exit child window
11930
        ImGuiWindow* child_window = g.NavWindow;
11931
        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
11932
        IM_ASSERT(child_window->ChildId != 0);
11933
        ImRect child_rect = child_window->Rect();
11934
        FocusWindow(parent_window);
11935
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
11936
        NavRestoreHighlightAfterMove();
11937
    }
11938
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
11939
    {
11940
        // Close open popup/menu
11941
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
11942
    }
11943
    else
11944
    {
11945
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
11946
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
11947
            g.NavWindow->NavLastIds[0] = 0;
11948
        g.NavId = 0;
11949
    }
11950
}
11951
11952
// Handle PageUp/PageDown/Home/End keys
11953
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
11954
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
11955
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
11956
static float ImGui::NavUpdatePageUpPageDown()
11957
{
11958
    ImGuiContext& g = *GImGui;
11959
    ImGuiWindow* window = g.NavWindow;
11960
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
11961
        return 0.0f;
11962
11963
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
11964
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
11965
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
11966
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
11967
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
11968
        return 0.0f;
11969
11970
    if (g.NavLayer != ImGuiNavLayer_Main)
11971
        NavRestoreLayer(ImGuiNavLayer_Main);
11972
11973
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll)
11974
    {
11975
        // Fallback manual-scroll when window has no navigable item
11976
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
11977
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
11978
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
11979
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
11980
        else if (home_pressed)
11981
            SetScrollY(window, 0.0f);
11982
        else if (end_pressed)
11983
            SetScrollY(window, window->ScrollMax.y);
11984
    }
11985
    else
11986
    {
11987
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
11988
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
11989
        float nav_scoring_rect_offset_y = 0.0f;
11990
        if (IsKeyPressed(ImGuiKey_PageUp, true))
11991
        {
11992
            nav_scoring_rect_offset_y = -page_offset_y;
11993
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
11994
            g.NavMoveClipDir = ImGuiDir_Up;
11995
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
11996
        }
11997
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
11998
        {
11999
            nav_scoring_rect_offset_y = +page_offset_y;
12000
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
12001
            g.NavMoveClipDir = ImGuiDir_Down;
12002
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12003
        }
12004
        else if (home_pressed)
12005
        {
12006
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12007
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12008
            // Preserve current horizontal position if we have any.
12009
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12010
            if (nav_rect_rel.IsInverted())
12011
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12012
            g.NavMoveDir = ImGuiDir_Down;
12013
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12014
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12015
        }
12016
        else if (end_pressed)
12017
        {
12018
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12019
            if (nav_rect_rel.IsInverted())
12020
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12021
            g.NavMoveDir = ImGuiDir_Up;
12022
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12023
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12024
        }
12025
        return nav_scoring_rect_offset_y;
12026
    }
12027
    return 0.0f;
12028
}
12029
12030
static void ImGui::NavEndFrame()
12031
{
12032
    ImGuiContext& g = *GImGui;
12033
12034
    // Show CTRL+TAB list window
12035
    if (g.NavWindowingTarget != NULL)
12036
        NavUpdateWindowingOverlay();
12037
12038
    // Perform wrap-around in menus
12039
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
12040
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12041
    const ImGuiNavMoveFlags wanted_flags = ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY;
12042
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & wanted_flags) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12043
        NavUpdateCreateWrappingRequest();
12044
}
12045
12046
static void ImGui::NavUpdateCreateWrappingRequest()
12047
{
12048
    ImGuiContext& g = *GImGui;
12049
    ImGuiWindow* window = g.NavWindow;
12050
12051
    bool do_forward = false;
12052
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
12053
    ImGuiDir clip_dir = g.NavMoveDir;
12054
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12055
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12056
    {
12057
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12058
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12059
        {
12060
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
12061
            clip_dir = ImGuiDir_Up;
12062
        }
12063
        do_forward = true;
12064
    }
12065
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12066
    {
12067
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12068
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12069
        {
12070
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
12071
            clip_dir = ImGuiDir_Down;
12072
        }
12073
        do_forward = true;
12074
    }
12075
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12076
    {
12077
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12078
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12079
        {
12080
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
12081
            clip_dir = ImGuiDir_Left;
12082
        }
12083
        do_forward = true;
12084
    }
12085
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12086
    {
12087
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12088
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12089
        {
12090
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
12091
            clip_dir = ImGuiDir_Right;
12092
        }
12093
        do_forward = true;
12094
    }
12095
    if (!do_forward)
12096
        return;
12097
    window->NavRectRel[g.NavLayer] = bb_rel;
12098
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
12099
}
12100
12101
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12102
{
12103
    ImGuiContext& g = *GImGui;
12104
    IM_UNUSED(g);
12105
    int order = window->FocusOrder;
12106
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12107
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
12108
    return order;
12109
}
12110
12111
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12112
{
12113
    ImGuiContext& g = *GImGui;
12114
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12115
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
12116
            return g.WindowsFocusOrder[i];
12117
    return NULL;
12118
}
12119
12120
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12121
{
12122
    ImGuiContext& g = *GImGui;
12123
    IM_ASSERT(g.NavWindowingTarget);
12124
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12125
        return;
12126
12127
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
12128
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
12129
    if (!window_target)
12130
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
12131
    if (window_target) // Don't reset windowing target if there's a single window in the list
12132
    {
12133
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12134
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12135
    }
12136
    g.NavWindowingToggleLayer = false;
12137
}
12138
12139
// Windowing management mode
12140
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12141
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12142
static void ImGui::NavUpdateWindowing()
12143
{
12144
    ImGuiContext& g = *GImGui;
12145
    ImGuiIO& io = g.IO;
12146
12147
    ImGuiWindow* apply_focus_window = NULL;
12148
    bool apply_toggle_layer = false;
12149
12150
    ImGuiWindow* modal_window = GetTopMostPopupModal();
12151
    bool allow_windowing = (modal_window == NULL);
12152
    if (!allow_windowing)
12153
        g.NavWindowingTarget = NULL;
12154
12155
    // Fade out
12156
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12157
    {
12158
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
12159
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12160
            g.NavWindowingTargetAnim = NULL;
12161
    }
12162
12163
    // Start CTRL+Tab or Square+L/R window selection
12164
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12165
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12166
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12167
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12168
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
12169
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
12170
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
12171
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
12172
        {
12173
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
12174
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
12175
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12176
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
12177
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
12178
        }
12179
12180
    // Gamepad update
12181
    g.NavWindowingTimer += io.DeltaTime;
12182
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
12183
    {
12184
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
12185
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
12186
12187
        // Select window to focus
12188
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
12189
        if (focus_change_dir != 0)
12190
        {
12191
            NavUpdateWindowingHighlightWindow(focus_change_dir);
12192
            g.NavWindowingHighlightAlpha = 1.0f;
12193
        }
12194
12195
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
12196
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
12197
        {
12198
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
12199
            if (g.NavWindowingToggleLayer && g.NavWindow)
12200
                apply_toggle_layer = true;
12201
            else if (!g.NavWindowingToggleLayer)
12202
                apply_focus_window = g.NavWindowingTarget;
12203
            g.NavWindowingTarget = NULL;
12204
        }
12205
    }
12206
12207
    // Keyboard: Focus
12208
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
12209
    {
12210
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
12211
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
12212
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
12213
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
12214
        if (keyboard_next_window || keyboard_prev_window)
12215
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
12216
        else if ((io.KeyMods & shared_mods) != shared_mods)
12217
            apply_focus_window = g.NavWindowingTarget;
12218
    }
12219
12220
    // Keyboard: Press and Release ALT to toggle menu layer
12221
    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
12222
    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
12223
    if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt, ImGuiKeyOwner_None))
12224
    {
12225
        g.NavWindowingToggleLayer = true;
12226
        g.NavInputSource = ImGuiInputSource_Keyboard;
12227
    }
12228
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
12229
    {
12230
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
12231
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
12232
        // We cancel toggling nav layer if an owner has claimed the key.
12233
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
12234
            g.NavWindowingToggleLayer = false;
12235
12236
        // Apply layer toggle on release
12237
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
12238
        if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
12239
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
12240
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
12241
                    apply_toggle_layer = true;
12242
        if (!IsKeyDown(ImGuiMod_Alt))
12243
            g.NavWindowingToggleLayer = false;
12244
    }
12245
12246
    // Move window
12247
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
12248
    {
12249
        ImVec2 nav_move_dir;
12250
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
12251
            nav_move_dir = GetKeyVector2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
12252
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
12253
            nav_move_dir = GetKeyVector2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12254
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
12255
        {
12256
            const float NAV_MOVE_SPEED = 800.0f;
12257
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
12258
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
12259
            g.NavDisableMouseHover = true;
12260
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaPos);
12261
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
12262
            {
12263
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
12264
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
12265
                g.NavWindowingAccumDeltaPos -= accum_floored;
12266
            }
12267
        }
12268
    }
12269
12270
    // Apply final focus
12271
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
12272
    {
12273
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
12274
        ClearActiveID();
12275
        NavRestoreHighlightAfterMove();
12276
        apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
12277
        ClosePopupsOverWindow(apply_focus_window, false);
12278
        FocusWindow(apply_focus_window);
12279
        if (apply_focus_window->NavLastIds[0] == 0)
12280
            NavInitWindow(apply_focus_window, false);
12281
12282
        // If the window has ONLY a menu layer (no main layer), select it directly
12283
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
12284
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
12285
        // the target window as already been previewed once.
12286
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
12287
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
12288
        // won't be valid.
12289
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
12290
            g.NavLayer = ImGuiNavLayer_Menu;
12291
12292
        // Request OS level focus
12293
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
12294
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
12295
    }
12296
    if (apply_focus_window)
12297
        g.NavWindowingTarget = NULL;
12298
12299
    // Apply menu/layer toggle
12300
    if (apply_toggle_layer && g.NavWindow)
12301
    {
12302
        ClearActiveID();
12303
12304
        // Move to parent menu if necessary
12305
        ImGuiWindow* new_nav_window = g.NavWindow;
12306
        while (new_nav_window->ParentWindow
12307
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
12308
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
12309
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12310
            new_nav_window = new_nav_window->ParentWindow;
12311
        if (new_nav_window != g.NavWindow)
12312
        {
12313
            ImGuiWindow* old_nav_window = g.NavWindow;
12314
            FocusWindow(new_nav_window);
12315
            new_nav_window->NavLastChildNavWindow = old_nav_window;
12316
        }
12317
12318
        // Toggle layer
12319
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
12320
        if (new_nav_layer != g.NavLayer)
12321
        {
12322
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
12323
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
12324
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
12325
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
12326
            NavRestoreLayer(new_nav_layer);
12327
            NavRestoreHighlightAfterMove();
12328
        }
12329
    }
12330
}
12331
12332
// Window has already passed the IsWindowNavFocusable()
12333
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
12334
{
12335
    if (window->Flags & ImGuiWindowFlags_Popup)
12336
        return "(Popup)";
12337
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
12338
        return "(Main menu bar)";
12339
    if (window->DockNodeAsHost)
12340
        return "(Dock node)";
12341
    return "(Untitled)";
12342
}
12343
12344
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
12345
void ImGui::NavUpdateWindowingOverlay()
12346
{
12347
    ImGuiContext& g = *GImGui;
12348
    IM_ASSERT(g.NavWindowingTarget != NULL);
12349
12350
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
12351
        return;
12352
12353
    if (g.NavWindowingListWindow == NULL)
12354
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
12355
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
12356
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
12357
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
12358
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
12359
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
12360
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
12361
    {
12362
        ImGuiWindow* window = g.WindowsFocusOrder[n];
12363
        IM_ASSERT(window != NULL); // Fix static analyzers
12364
        if (!IsWindowNavFocusable(window))
12365
            continue;
12366
        const char* label = window->Name;
12367
        if (label == FindRenderedTextEnd(label))
12368
            label = GetFallbackWindowNameForWindowingList(window);
12369
        Selectable(label, g.NavWindowingTarget == window);
12370
    }
12371
    End();
12372
    PopStyleVar();
12373
}
12374
12375
12376
//-----------------------------------------------------------------------------
12377
// [SECTION] DRAG AND DROP
12378
//-----------------------------------------------------------------------------
12379
12380
bool ImGui::IsDragDropActive()
12381
{
12382
    ImGuiContext& g = *GImGui;
12383
    return g.DragDropActive;
12384
}
12385
12386
void ImGui::ClearDragDrop()
12387
{
12388
    ImGuiContext& g = *GImGui;
12389
    g.DragDropActive = false;
12390
    g.DragDropPayload.Clear();
12391
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
12392
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
12393
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
12394
    g.DragDropAcceptFrameCount = -1;
12395
12396
    g.DragDropPayloadBufHeap.clear();
12397
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12398
}
12399
12400
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
12401
// If the item has an identifier:
12402
// - This assume/require the item to be activated (typically via ButtonBehavior).
12403
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
12404
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
12405
// If the item has no identifier:
12406
// - Currently always assume left mouse button.
12407
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
12408
{
12409
    ImGuiContext& g = *GImGui;
12410
    ImGuiWindow* window = g.CurrentWindow;
12411
12412
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
12413
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
12414
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
12415
12416
    bool source_drag_active = false;
12417
    ImGuiID source_id = 0;
12418
    ImGuiID source_parent_id = 0;
12419
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
12420
    {
12421
        source_id = g.LastItemData.ID;
12422
        if (source_id != 0)
12423
        {
12424
            // Common path: items with ID
12425
            if (g.ActiveId != source_id)
12426
                return false;
12427
            if (g.ActiveIdMouseButton != -1)
12428
                mouse_button = g.ActiveIdMouseButton;
12429
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12430
                return false;
12431
            g.ActiveIdAllowOverlap = false;
12432
        }
12433
        else
12434
        {
12435
            // Uncommon path: items without ID
12436
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12437
                return false;
12438
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
12439
                return false;
12440
12441
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
12442
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
12443
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
12444
            {
12445
                IM_ASSERT(0);
12446
                return false;
12447
            }
12448
12449
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
12450
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
12451
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
12452
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
12453
            // Rely on keeping other window->LastItemXXX fields intact.
12454
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
12455
            KeepAliveID(source_id);
12456
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id);
12457
            if (is_hovered && g.IO.MouseClicked[mouse_button])
12458
            {
12459
                SetActiveID(source_id, window);
12460
                FocusWindow(window);
12461
            }
12462
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
12463
                g.ActiveIdAllowOverlap = is_hovered;
12464
        }
12465
        if (g.ActiveId != source_id)
12466
            return false;
12467
        source_parent_id = window->IDStack.back();
12468
        source_drag_active = IsMouseDragging(mouse_button);
12469
12470
        // Disable navigation and key inputs while dragging + cancel existing request if any
12471
        SetActiveIdUsingAllKeyboardKeys();
12472
    }
12473
    else
12474
    {
12475
        window = NULL;
12476
        source_id = ImHashStr("#SourceExtern");
12477
        source_drag_active = true;
12478
    }
12479
12480
    if (source_drag_active)
12481
    {
12482
        if (!g.DragDropActive)
12483
        {
12484
            IM_ASSERT(source_id != 0);
12485
            ClearDragDrop();
12486
            ImGuiPayload& payload = g.DragDropPayload;
12487
            payload.SourceId = source_id;
12488
            payload.SourceParentId = source_parent_id;
12489
            g.DragDropActive = true;
12490
            g.DragDropSourceFlags = flags;
12491
            g.DragDropMouseButton = mouse_button;
12492
            if (payload.SourceId == g.ActiveId)
12493
                g.ActiveIdNoClearOnFocusLoss = true;
12494
        }
12495
        g.DragDropSourceFrameCount = g.FrameCount;
12496
        g.DragDropWithinSource = true;
12497
12498
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12499
        {
12500
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
12501
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
12502
            BeginTooltip();
12503
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
12504
            {
12505
                ImGuiWindow* tooltip_window = g.CurrentWindow;
12506
                tooltip_window->Hidden = tooltip_window->SkipItems = true;
12507
                tooltip_window->HiddenFramesCanSkipItems = 1;
12508
            }
12509
        }
12510
12511
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
12512
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
12513
12514
        return true;
12515
    }
12516
    return false;
12517
}
12518
12519
void ImGui::EndDragDropSource()
12520
{
12521
    ImGuiContext& g = *GImGui;
12522
    IM_ASSERT(g.DragDropActive);
12523
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
12524
12525
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12526
        EndTooltip();
12527
12528
    // Discard the drag if have not called SetDragDropPayload()
12529
    if (g.DragDropPayload.DataFrameCount == -1)
12530
        ClearDragDrop();
12531
    g.DragDropWithinSource = false;
12532
}
12533
12534
// Use 'cond' to choose to submit payload on drag start or every frame
12535
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
12536
{
12537
    ImGuiContext& g = *GImGui;
12538
    ImGuiPayload& payload = g.DragDropPayload;
12539
    if (cond == 0)
12540
        cond = ImGuiCond_Always;
12541
12542
    IM_ASSERT(type != NULL);
12543
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
12544
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
12545
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
12546
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
12547
12548
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
12549
    {
12550
        // Copy payload
12551
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
12552
        g.DragDropPayloadBufHeap.resize(0);
12553
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
12554
        {
12555
            // Store in heap
12556
            g.DragDropPayloadBufHeap.resize((int)data_size);
12557
            payload.Data = g.DragDropPayloadBufHeap.Data;
12558
            memcpy(payload.Data, data, data_size);
12559
        }
12560
        else if (data_size > 0)
12561
        {
12562
            // Store locally
12563
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12564
            payload.Data = g.DragDropPayloadBufLocal;
12565
            memcpy(payload.Data, data, data_size);
12566
        }
12567
        else
12568
        {
12569
            payload.Data = NULL;
12570
        }
12571
        payload.DataSize = (int)data_size;
12572
    }
12573
    payload.DataFrameCount = g.FrameCount;
12574
12575
    // Return whether the payload has been accepted
12576
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
12577
}
12578
12579
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
12580
{
12581
    ImGuiContext& g = *GImGui;
12582
    if (!g.DragDropActive)
12583
        return false;
12584
12585
    ImGuiWindow* window = g.CurrentWindow;
12586
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
12587
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
12588
        return false;
12589
    IM_ASSERT(id != 0);
12590
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
12591
        return false;
12592
    if (window->SkipItems)
12593
        return false;
12594
12595
    IM_ASSERT(g.DragDropWithinTarget == false);
12596
    g.DragDropTargetRect = bb;
12597
    g.DragDropTargetId = id;
12598
    g.DragDropWithinTarget = true;
12599
    return true;
12600
}
12601
12602
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
12603
// 1) we use LastItemRectHoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
12604
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
12605
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
12606
bool ImGui::BeginDragDropTarget()
12607
{
12608
    ImGuiContext& g = *GImGui;
12609
    if (!g.DragDropActive)
12610
        return false;
12611
12612
    ImGuiWindow* window = g.CurrentWindow;
12613
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
12614
        return false;
12615
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
12616
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
12617
        return false;
12618
12619
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
12620
    ImGuiID id = g.LastItemData.ID;
12621
    if (id == 0)
12622
    {
12623
        id = window->GetIDFromRectangle(display_rect);
12624
        KeepAliveID(id);
12625
    }
12626
    if (g.DragDropPayload.SourceId == id)
12627
        return false;
12628
12629
    IM_ASSERT(g.DragDropWithinTarget == false);
12630
    g.DragDropTargetRect = display_rect;
12631
    g.DragDropTargetId = id;
12632
    g.DragDropWithinTarget = true;
12633
    return true;
12634
}
12635
12636
bool ImGui::IsDragDropPayloadBeingAccepted()
12637
{
12638
    ImGuiContext& g = *GImGui;
12639
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
12640
}
12641
12642
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
12643
{
12644
    ImGuiContext& g = *GImGui;
12645
    ImGuiWindow* window = g.CurrentWindow;
12646
    ImGuiPayload& payload = g.DragDropPayload;
12647
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
12648
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
12649
    if (type != NULL && !payload.IsDataType(type))
12650
        return NULL;
12651
12652
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
12653
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
12654
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
12655
    ImRect r = g.DragDropTargetRect;
12656
    float r_surface = r.GetWidth() * r.GetHeight();
12657
    if (r_surface <= g.DragDropAcceptIdCurrRectSurface)
12658
    {
12659
        g.DragDropAcceptFlags = flags;
12660
        g.DragDropAcceptIdCurr = g.DragDropTargetId;
12661
        g.DragDropAcceptIdCurrRectSurface = r_surface;
12662
    }
12663
12664
    // Render default drop visuals
12665
    payload.Preview = was_accepted_previously;
12666
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
12667
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
12668
        window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
12669
12670
    g.DragDropAcceptFrameCount = g.FrameCount;
12671
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
12672
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
12673
        return NULL;
12674
12675
    return &payload;
12676
}
12677
12678
// FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
12679
void ImGui::RenderDragDropTargetRect(const ImRect& bb)
12680
{
12681
    GetWindowDrawList()->AddRect(bb.Min - ImVec2(3.5f, 3.5f), bb.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
12682
}
12683
12684
const ImGuiPayload* ImGui::GetDragDropPayload()
12685
{
12686
    ImGuiContext& g = *GImGui;
12687
    return g.DragDropActive ? &g.DragDropPayload : NULL;
12688
}
12689
12690
// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
12691
void ImGui::EndDragDropTarget()
12692
{
12693
    ImGuiContext& g = *GImGui;
12694
    IM_ASSERT(g.DragDropActive);
12695
    IM_ASSERT(g.DragDropWithinTarget);
12696
    g.DragDropWithinTarget = false;
12697
}
12698
12699
//-----------------------------------------------------------------------------
12700
// [SECTION] LOGGING/CAPTURING
12701
//-----------------------------------------------------------------------------
12702
// All text output from the interface can be captured into tty/file/clipboard.
12703
// By default, tree nodes are automatically opened during logging.
12704
//-----------------------------------------------------------------------------
12705
12706
// Pass text data straight to log (without being displayed)
12707
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
12708
{
12709
    if (g.LogFile)
12710
    {
12711
        g.LogBuffer.Buf.resize(0);
12712
        g.LogBuffer.appendfv(fmt, args);
12713
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
12714
    }
12715
    else
12716
    {
12717
        g.LogBuffer.appendfv(fmt, args);
12718
    }
12719
}
12720
12721
void ImGui::LogText(const char* fmt, ...)
12722
{
12723
    ImGuiContext& g = *GImGui;
12724
    if (!g.LogEnabled)
12725
        return;
12726
12727
    va_list args;
12728
    va_start(args, fmt);
12729
    LogTextV(g, fmt, args);
12730
    va_end(args);
12731
}
12732
12733
void ImGui::LogTextV(const char* fmt, va_list args)
12734
{
12735
    ImGuiContext& g = *GImGui;
12736
    if (!g.LogEnabled)
12737
        return;
12738
12739
    LogTextV(g, fmt, args);
12740
}
12741
12742
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
12743
// We split text into individual lines to add current tree level padding
12744
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
12745
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
12746
{
12747
    ImGuiContext& g = *GImGui;
12748
    ImGuiWindow* window = g.CurrentWindow;
12749
12750
    const char* prefix = g.LogNextPrefix;
12751
    const char* suffix = g.LogNextSuffix;
12752
    g.LogNextPrefix = g.LogNextSuffix = NULL;
12753
12754
    if (!text_end)
12755
        text_end = FindRenderedTextEnd(text, text_end);
12756
12757
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
12758
    if (ref_pos)
12759
        g.LogLinePosY = ref_pos->y;
12760
    if (log_new_line)
12761
    {
12762
        LogText(IM_NEWLINE);
12763
        g.LogLineFirstItem = true;
12764
    }
12765
12766
    if (prefix)
12767
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
12768
12769
    // Re-adjust padding if we have popped out of our starting depth
12770
    if (g.LogDepthRef > window->DC.TreeDepth)
12771
        g.LogDepthRef = window->DC.TreeDepth;
12772
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
12773
12774
    const char* text_remaining = text;
12775
    for (;;)
12776
    {
12777
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
12778
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
12779
        const char* line_start = text_remaining;
12780
        const char* line_end = ImStreolRange(line_start, text_end);
12781
        const bool is_last_line = (line_end == text_end);
12782
        if (line_start != line_end || !is_last_line)
12783
        {
12784
            const int line_length = (int)(line_end - line_start);
12785
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
12786
            LogText("%*s%.*s", indentation, "", line_length, line_start);
12787
            g.LogLineFirstItem = false;
12788
            if (*line_end == '\n')
12789
            {
12790
                LogText(IM_NEWLINE);
12791
                g.LogLineFirstItem = true;
12792
            }
12793
        }
12794
        if (is_last_line)
12795
            break;
12796
        text_remaining = line_end + 1;
12797
    }
12798
12799
    if (suffix)
12800
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
12801
}
12802
12803
// Start logging/capturing text output
12804
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
12805
{
12806
    ImGuiContext& g = *GImGui;
12807
    ImGuiWindow* window = g.CurrentWindow;
12808
    IM_ASSERT(g.LogEnabled == false);
12809
    IM_ASSERT(g.LogFile == NULL);
12810
    IM_ASSERT(g.LogBuffer.empty());
12811
    g.LogEnabled = true;
12812
    g.LogType = type;
12813
    g.LogNextPrefix = g.LogNextSuffix = NULL;
12814
    g.LogDepthRef = window->DC.TreeDepth;
12815
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
12816
    g.LogLinePosY = FLT_MAX;
12817
    g.LogLineFirstItem = true;
12818
}
12819
12820
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
12821
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
12822
{
12823
    ImGuiContext& g = *GImGui;
12824
    g.LogNextPrefix = prefix;
12825
    g.LogNextSuffix = suffix;
12826
}
12827
12828
void ImGui::LogToTTY(int auto_open_depth)
12829
{
12830
    ImGuiContext& g = *GImGui;
12831
    if (g.LogEnabled)
12832
        return;
12833
    IM_UNUSED(auto_open_depth);
12834
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
12835
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
12836
    g.LogFile = stdout;
12837
#endif
12838
}
12839
12840
// Start logging/capturing text output to given file
12841
void ImGui::LogToFile(int auto_open_depth, const char* filename)
12842
{
12843
    ImGuiContext& g = *GImGui;
12844
    if (g.LogEnabled)
12845
        return;
12846
12847
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
12848
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
12849
    // By opening the file in binary mode "ab" we have consistent output everywhere.
12850
    if (!filename)
12851
        filename = g.IO.LogFilename;
12852
    if (!filename || !filename[0])
12853
        return;
12854
    ImFileHandle f = ImFileOpen(filename, "ab");
12855
    if (!f)
12856
    {
12857
        IM_ASSERT(0);
12858
        return;
12859
    }
12860
12861
    LogBegin(ImGuiLogType_File, auto_open_depth);
12862
    g.LogFile = f;
12863
}
12864
12865
// Start logging/capturing text output to clipboard
12866
void ImGui::LogToClipboard(int auto_open_depth)
12867
{
12868
    ImGuiContext& g = *GImGui;
12869
    if (g.LogEnabled)
12870
        return;
12871
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
12872
}
12873
12874
void ImGui::LogToBuffer(int auto_open_depth)
12875
{
12876
    ImGuiContext& g = *GImGui;
12877
    if (g.LogEnabled)
12878
        return;
12879
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
12880
}
12881
12882
void ImGui::LogFinish()
12883
{
12884
    ImGuiContext& g = *GImGui;
12885
    if (!g.LogEnabled)
12886
        return;
12887
12888
    LogText(IM_NEWLINE);
12889
    switch (g.LogType)
12890
    {
12891
    case ImGuiLogType_TTY:
12892
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
12893
        fflush(g.LogFile);
12894
#endif
12895
        break;
12896
    case ImGuiLogType_File:
12897
        ImFileClose(g.LogFile);
12898
        break;
12899
    case ImGuiLogType_Buffer:
12900
        break;
12901
    case ImGuiLogType_Clipboard:
12902
        if (!g.LogBuffer.empty())
12903
            SetClipboardText(g.LogBuffer.begin());
12904
        break;
12905
    case ImGuiLogType_None:
12906
        IM_ASSERT(0);
12907
        break;
12908
    }
12909
12910
    g.LogEnabled = false;
12911
    g.LogType = ImGuiLogType_None;
12912
    g.LogFile = NULL;
12913
    g.LogBuffer.clear();
12914
}
12915
12916
// Helper to display logging buttons
12917
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
12918
void ImGui::LogButtons()
12919
{
12920
    ImGuiContext& g = *GImGui;
12921
12922
    PushID("LogButtons");
12923
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
12924
    const bool log_to_tty = Button("Log To TTY"); SameLine();
12925
#else
12926
    const bool log_to_tty = false;
12927
#endif
12928
    const bool log_to_file = Button("Log To File"); SameLine();
12929
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
12930
    PushAllowKeyboardFocus(false);
12931
    SetNextItemWidth(80.0f);
12932
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
12933
    PopAllowKeyboardFocus();
12934
    PopID();
12935
12936
    // Start logging at the end of the function so that the buttons don't appear in the log
12937
    if (log_to_tty)
12938
        LogToTTY();
12939
    if (log_to_file)
12940
        LogToFile();
12941
    if (log_to_clipboard)
12942
        LogToClipboard();
12943
}
12944
12945
12946
//-----------------------------------------------------------------------------
12947
// [SECTION] SETTINGS
12948
//-----------------------------------------------------------------------------
12949
// - UpdateSettings() [Internal]
12950
// - MarkIniSettingsDirty() [Internal]
12951
// - CreateNewWindowSettings() [Internal]
12952
// - FindWindowSettings() [Internal]
12953
// - FindOrCreateWindowSettings() [Internal]
12954
// - FindSettingsHandler() [Internal]
12955
// - ClearIniSettings() [Internal]
12956
// - LoadIniSettingsFromDisk()
12957
// - LoadIniSettingsFromMemory()
12958
// - SaveIniSettingsToDisk()
12959
// - SaveIniSettingsToMemory()
12960
// - WindowSettingsHandler_***() [Internal]
12961
//-----------------------------------------------------------------------------
12962
12963
// Called by NewFrame()
12964
void ImGui::UpdateSettings()
12965
{
12966
    // Load settings on first frame (if not explicitly loaded manually before)
12967
    ImGuiContext& g = *GImGui;
12968
    if (!g.SettingsLoaded)
12969
    {
12970
        IM_ASSERT(g.SettingsWindows.empty());
12971
        if (g.IO.IniFilename)
12972
            LoadIniSettingsFromDisk(g.IO.IniFilename);
12973
        g.SettingsLoaded = true;
12974
    }
12975
12976
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
12977
    if (g.SettingsDirtyTimer > 0.0f)
12978
    {
12979
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
12980
        if (g.SettingsDirtyTimer <= 0.0f)
12981
        {
12982
            if (g.IO.IniFilename != NULL)
12983
                SaveIniSettingsToDisk(g.IO.IniFilename);
12984
            else
12985
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
12986
            g.SettingsDirtyTimer = 0.0f;
12987
        }
12988
    }
12989
}
12990
12991
void ImGui::MarkIniSettingsDirty()
12992
{
12993
    ImGuiContext& g = *GImGui;
12994
    if (g.SettingsDirtyTimer <= 0.0f)
12995
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
12996
}
12997
12998
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
12999
{
13000
    ImGuiContext& g = *GImGui;
13001
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13002
        if (g.SettingsDirtyTimer <= 0.0f)
13003
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
13004
}
13005
13006
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
13007
{
13008
    ImGuiContext& g = *GImGui;
13009
13010
#if !IMGUI_DEBUG_INI_SETTINGS
13011
    // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
13012
    // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
13013
    if (const char* p = strstr(name, "###"))
13014
        name = p;
13015
#endif
13016
    const size_t name_len = strlen(name);
13017
13018
    // Allocate chunk
13019
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
13020
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
13021
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
13022
    settings->ID = ImHashStr(name, name_len);
13023
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
13024
13025
    return settings;
13026
}
13027
13028
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
13029
{
13030
    ImGuiContext& g = *GImGui;
13031
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13032
        if (settings->ID == id)
13033
            return settings;
13034
    return NULL;
13035
}
13036
13037
ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
13038
{
13039
    if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
13040
        return settings;
13041
    return CreateNewWindowSettings(name);
13042
}
13043
13044
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13045
{
13046
    ImGuiContext& g = *GImGui;
13047
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13048
    g.SettingsHandlers.push_back(*handler);
13049
}
13050
13051
void ImGui::RemoveSettingsHandler(const char* type_name)
13052
{
13053
    ImGuiContext& g = *GImGui;
13054
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13055
        g.SettingsHandlers.erase(handler);
13056
}
13057
13058
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13059
{
13060
    ImGuiContext& g = *GImGui;
13061
    const ImGuiID type_hash = ImHashStr(type_name);
13062
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13063
        if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
13064
            return &g.SettingsHandlers[handler_n];
13065
    return NULL;
13066
}
13067
13068
void ImGui::ClearIniSettings()
13069
{
13070
    ImGuiContext& g = *GImGui;
13071
    g.SettingsIniData.clear();
13072
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13073
        if (g.SettingsHandlers[handler_n].ClearAllFn)
13074
            g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
13075
}
13076
13077
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13078
{
13079
    size_t file_data_size = 0;
13080
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
13081
    if (!file_data)
13082
        return;
13083
    if (file_data_size > 0)
13084
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
13085
    IM_FREE(file_data);
13086
}
13087
13088
// Zero-tolerance, no error reporting, cheap .ini parsing
13089
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13090
{
13091
    ImGuiContext& g = *GImGui;
13092
    IM_ASSERT(g.Initialized);
13093
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13094
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13095
13096
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13097
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
13098
    if (ini_size == 0)
13099
        ini_size = strlen(ini_data);
13100
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
13101
    char* const buf = g.SettingsIniData.Buf.Data;
13102
    char* const buf_end = buf + ini_size;
13103
    memcpy(buf, ini_data, ini_size);
13104
    buf_end[0] = 0;
13105
13106
    // Call pre-read handlers
13107
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13108
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13109
        if (g.SettingsHandlers[handler_n].ReadInitFn)
13110
            g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
13111
13112
    void* entry_data = NULL;
13113
    ImGuiSettingsHandler* entry_handler = NULL;
13114
13115
    char* line_end = NULL;
13116
    for (char* line = buf; line < buf_end; line = line_end + 1)
13117
    {
13118
        // Skip new lines markers, then find end of the line
13119
        while (*line == '\n' || *line == '\r')
13120
            line++;
13121
        line_end = line;
13122
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13123
            line_end++;
13124
        line_end[0] = 0;
13125
        if (line[0] == ';')
13126
            continue;
13127
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13128
        {
13129
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13130
            line_end[-1] = 0;
13131
            const char* name_end = line_end - 1;
13132
            const char* type_start = line + 1;
13133
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
13134
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
13135
            if (!type_end || !name_start)
13136
                continue;
13137
            *type_end = 0; // Overwrite first ']'
13138
            name_start++;  // Skip second '['
13139
            entry_handler = FindSettingsHandler(type_start);
13140
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13141
        }
13142
        else if (entry_handler != NULL && entry_data != NULL)
13143
        {
13144
            // Let type handler parse the line
13145
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13146
        }
13147
    }
13148
    g.SettingsLoaded = true;
13149
13150
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13151
    memcpy(buf, ini_data, ini_size);
13152
13153
    // Call post-read handlers
13154
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13155
        if (g.SettingsHandlers[handler_n].ApplyAllFn)
13156
            g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
13157
}
13158
13159
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
13160
{
13161
    ImGuiContext& g = *GImGui;
13162
    g.SettingsDirtyTimer = 0.0f;
13163
    if (!ini_filename)
13164
        return;
13165
13166
    size_t ini_data_size = 0;
13167
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
13168
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
13169
    if (!f)
13170
        return;
13171
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
13172
    ImFileClose(f);
13173
}
13174
13175
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
13176
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
13177
{
13178
    ImGuiContext& g = *GImGui;
13179
    g.SettingsDirtyTimer = 0.0f;
13180
    g.SettingsIniData.Buf.resize(0);
13181
    g.SettingsIniData.Buf.push_back(0);
13182
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13183
    {
13184
        ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
13185
        handler->WriteAllFn(&g, handler, &g.SettingsIniData);
13186
    }
13187
    if (out_size)
13188
        *out_size = (size_t)g.SettingsIniData.size();
13189
    return g.SettingsIniData.c_str();
13190
}
13191
13192
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13193
{
13194
    ImGuiContext& g = *ctx;
13195
    for (int i = 0; i != g.Windows.Size; i++)
13196
        g.Windows[i]->SettingsOffset = -1;
13197
    g.SettingsWindows.clear();
13198
}
13199
13200
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
13201
{
13202
    ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name);
13203
    ImGuiID id = settings->ID;
13204
    *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
13205
    settings->ID = id;
13206
    settings->WantApply = true;
13207
    return (void*)settings;
13208
}
13209
13210
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
13211
{
13212
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
13213
    int x, y;
13214
    int i;
13215
    ImU32 u1;
13216
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
13217
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
13218
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
13219
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
13220
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
13221
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
13222
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
13223
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
13224
}
13225
13226
// Apply to existing windows (if any)
13227
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13228
{
13229
    ImGuiContext& g = *ctx;
13230
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13231
        if (settings->WantApply)
13232
        {
13233
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
13234
                ApplyWindowSettings(window, settings);
13235
            settings->WantApply = false;
13236
        }
13237
}
13238
13239
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
13240
{
13241
    // Gather data from windows that were active during this session
13242
    // (if a window wasn't opened in this session we preserve its settings)
13243
    ImGuiContext& g = *ctx;
13244
    for (int i = 0; i != g.Windows.Size; i++)
13245
    {
13246
        ImGuiWindow* window = g.Windows[i];
13247
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
13248
            continue;
13249
13250
        ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
13251
        if (!settings)
13252
        {
13253
            settings = ImGui::CreateNewWindowSettings(window->Name);
13254
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
13255
        }
13256
        IM_ASSERT(settings->ID == window->ID);
13257
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
13258
        settings->Size = ImVec2ih(window->SizeFull);
13259
        settings->ViewportId = window->ViewportId;
13260
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
13261
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
13262
        settings->DockId = window->DockId;
13263
        settings->ClassId = window->WindowClass.ClassId;
13264
        settings->DockOrder = window->DockOrder;
13265
        settings->Collapsed = window->Collapsed;
13266
    }
13267
13268
    // Write to text buffer
13269
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
13270
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13271
    {
13272
        const char* settings_name = settings->GetName();
13273
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
13274
        if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13275
        {
13276
            buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
13277
            buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
13278
        }
13279
        if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13280
            buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
13281
        if (settings->Size.x != 0 || settings->Size.y != 0)
13282
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
13283
        buf->appendf("Collapsed=%d\n", settings->Collapsed);
13284
        if (settings->DockId != 0)
13285
        {
13286
            //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
13287
            if (settings->DockOrder == -1)
13288
                buf->appendf("DockId=0x%08X\n", settings->DockId);
13289
            else
13290
                buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
13291
            if (settings->ClassId != 0)
13292
                buf->appendf("ClassId=0x%08X\n", settings->ClassId);
13293
        }
13294
        buf->append("\n");
13295
    }
13296
}
13297
13298
13299
//-----------------------------------------------------------------------------
13300
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
13301
//-----------------------------------------------------------------------------
13302
// - GetMainViewport()
13303
// - FindViewportByID()
13304
// - FindViewportByPlatformHandle()
13305
// - SetCurrentViewport() [Internal]
13306
// - SetWindowViewport() [Internal]
13307
// - GetWindowAlwaysWantOwnViewport() [Internal]
13308
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
13309
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
13310
// - TranslateWindowsInViewport() [Internal]
13311
// - ScaleWindowsInViewport() [Internal]
13312
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
13313
// - UpdateViewportsNewFrame() [Internal]
13314
// - UpdateViewportsEndFrame() [Internal]
13315
// - AddUpdateViewport() [Internal]
13316
// - WindowSelectViewport() [Internal]
13317
// - WindowSyncOwnedViewport() [Internal]
13318
// - UpdatePlatformWindows()
13319
// - RenderPlatformWindowsDefault()
13320
// - FindPlatformMonitorForPos() [Internal]
13321
// - FindPlatformMonitorForRect() [Internal]
13322
// - UpdateViewportPlatformMonitor() [Internal]
13323
// - DestroyPlatformWindow() [Internal]
13324
// - DestroyPlatformWindows()
13325
//-----------------------------------------------------------------------------
13326
13327
ImGuiViewport* ImGui::GetMainViewport()
13328
{
13329
    ImGuiContext& g = *GImGui;
13330
    return g.Viewports[0];
13331
}
13332
13333
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
13334
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
13335
{
13336
    ImGuiContext& g = *GImGui;
13337
    for (int n = 0; n < g.Viewports.Size; n++)
13338
        if (g.Viewports[n]->ID == id)
13339
            return g.Viewports[n];
13340
    return NULL;
13341
}
13342
13343
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
13344
{
13345
    ImGuiContext& g = *GImGui;
13346
    for (int i = 0; i != g.Viewports.Size; i++)
13347
        if (g.Viewports[i]->PlatformHandle == platform_handle)
13348
            return g.Viewports[i];
13349
    return NULL;
13350
}
13351
13352
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
13353
{
13354
    ImGuiContext& g = *GImGui;
13355
    (void)current_window;
13356
13357
    if (viewport)
13358
        viewport->LastFrameActive = g.FrameCount;
13359
    if (g.CurrentViewport == viewport)
13360
        return;
13361
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
13362
    g.CurrentViewport = viewport;
13363
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
13364
13365
    // Notify platform layer of viewport changes
13366
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
13367
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
13368
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
13369
}
13370
13371
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13372
{
13373
    // Abandon viewport
13374
    if (window->ViewportOwned && window->Viewport->Window == window)
13375
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
13376
13377
    window->Viewport = viewport;
13378
    window->ViewportId = viewport->ID;
13379
    window->ViewportOwned = (viewport->Window == window);
13380
}
13381
13382
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
13383
{
13384
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
13385
    ImGuiContext& g = *GImGui;
13386
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
13387
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
13388
            if (!window->DockIsActive)
13389
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
13390
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
13391
                        return true;
13392
    return false;
13393
}
13394
13395
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13396
{
13397
    ImGuiContext& g = *GImGui;
13398
    if (window->Viewport == viewport)
13399
        return false;
13400
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
13401
        return false;
13402
    if ((viewport->Flags & ImGuiViewportFlags_Minimized) != 0)
13403
        return false;
13404
    if (!viewport->GetMainRect().Contains(window->Rect()))
13405
        return false;
13406
    if (GetWindowAlwaysWantOwnViewport(window))
13407
        return false;
13408
13409
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
13410
    for (int n = 0; n < g.Windows.Size; n++)
13411
    {
13412
        ImGuiWindow* window_behind = g.Windows[n];
13413
        if (window_behind == window)
13414
            break;
13415
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
13416
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
13417
                return false;
13418
    }
13419
13420
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
13421
    ImGuiViewportP* old_viewport = window->Viewport;
13422
    if (window->ViewportOwned)
13423
        for (int n = 0; n < g.Windows.Size; n++)
13424
            if (g.Windows[n]->Viewport == old_viewport)
13425
                SetWindowViewport(g.Windows[n], viewport);
13426
    SetWindowViewport(window, viewport);
13427
    BringWindowToDisplayFront(window);
13428
13429
    return true;
13430
}
13431
13432
// FIXME: handle 0 to N host viewports
13433
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
13434
{
13435
    ImGuiContext& g = *GImGui;
13436
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
13437
}
13438
13439
// Translate Dear ImGui windows when a Host Viewport has been moved
13440
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
13441
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
13442
{
13443
    ImGuiContext& g = *GImGui;
13444
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
13445
13446
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
13447
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
13448
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
13449
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
13450
    // and so the window will appear to teleport when releasing the mouse.
13451
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
13452
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
13453
    ImVec2 delta_pos = new_pos - old_pos;
13454
    for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT
13455
        if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect())))
13456
            TranslateWindow(g.Windows[window_n], delta_pos);
13457
}
13458
13459
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
13460
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
13461
{
13462
    ImGuiContext& g = *GImGui;
13463
    if (viewport->Window)
13464
    {
13465
        ScaleWindow(viewport->Window, scale);
13466
    }
13467
    else
13468
    {
13469
        for (int i = 0; i != g.Windows.Size; i++)
13470
            if (g.Windows[i]->Viewport == viewport)
13471
                ScaleWindow(g.Windows[i], scale);
13472
    }
13473
}
13474
13475
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
13476
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
13477
// B) It requires Platform_GetWindowFocus to be implemented by backend.
13478
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
13479
{
13480
    ImGuiContext& g = *GImGui;
13481
    ImGuiViewportP* best_candidate = NULL;
13482
    for (int n = 0; n < g.Viewports.Size; n++)
13483
    {
13484
        ImGuiViewportP* viewport = g.Viewports[n];
13485
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_Minimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
13486
            if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount)
13487
                best_candidate = viewport;
13488
    }
13489
    return best_candidate;
13490
}
13491
13492
// Update viewports and monitor infos
13493
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
13494
static void ImGui::UpdateViewportsNewFrame()
13495
{
13496
    ImGuiContext& g = *GImGui;
13497
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
13498
13499
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
13500
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
13501
    if (viewports_enabled)
13502
    {
13503
        for (int n = 0; n < g.Viewports.Size; n++)
13504
        {
13505
            ImGuiViewportP* viewport = g.Viewports[n];
13506
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
13507
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
13508
            {
13509
                bool minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
13510
                if (minimized)
13511
                    viewport->Flags |= ImGuiViewportFlags_Minimized;
13512
                else
13513
                    viewport->Flags &= ~ImGuiViewportFlags_Minimized;
13514
            }
13515
        }
13516
    }
13517
13518
    // Create/update main viewport with current platform position.
13519
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
13520
    ImGuiViewportP* main_viewport = g.Viewports[0];
13521
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
13522
    IM_ASSERT(main_viewport->Window == NULL);
13523
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
13524
    ImVec2 main_viewport_size = g.IO.DisplaySize;
13525
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_Minimized))
13526
    {
13527
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
13528
        main_viewport_size = main_viewport->Size;
13529
    }
13530
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
13531
13532
    g.CurrentDpiScale = 0.0f;
13533
    g.CurrentViewport = NULL;
13534
    g.MouseViewport = NULL;
13535
    for (int n = 0; n < g.Viewports.Size; n++)
13536
    {
13537
        ImGuiViewportP* viewport = g.Viewports[n];
13538
        viewport->Idx = n;
13539
13540
        // Erase unused viewports
13541
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
13542
        {
13543
            DestroyViewport(viewport);
13544
            n--;
13545
            continue;
13546
        }
13547
13548
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
13549
        if (viewports_enabled)
13550
        {
13551
            // Update Position and Size (from Platform Window to ImGui) if requested.
13552
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
13553
            if (!(viewport->Flags & ImGuiViewportFlags_Minimized) && platform_funcs_available)
13554
            {
13555
                // Viewport->WorkPos and WorkSize will be updated below
13556
                if (viewport->PlatformRequestMove)
13557
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
13558
                if (viewport->PlatformRequestResize)
13559
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
13560
            }
13561
        }
13562
13563
        // Update/copy monitor info
13564
        UpdateViewportPlatformMonitor(viewport);
13565
13566
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
13567
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
13568
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
13569
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
13570
        viewport->UpdateWorkRect();
13571
13572
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
13573
        viewport->Alpha = 1.0f;
13574
13575
        // Translate Dear ImGui windows when a Host Viewport has been moved
13576
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
13577
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
13578
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
13579
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
13580
13581
        // Update DPI scale
13582
        float new_dpi_scale;
13583
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
13584
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
13585
        else if (viewport->PlatformMonitor != -1)
13586
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
13587
        else
13588
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
13589
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
13590
        {
13591
            float scale_factor = new_dpi_scale / viewport->DpiScale;
13592
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
13593
                ScaleWindowsInViewport(viewport, scale_factor);
13594
            //if (viewport == GetMainViewport())
13595
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
13596
13597
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
13598
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
13599
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
13600
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
13601
            //    g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor);
13602
        }
13603
        viewport->DpiScale = new_dpi_scale;
13604
    }
13605
13606
    // Update fallback monitor
13607
    if (g.PlatformIO.Monitors.Size == 0)
13608
    {
13609
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
13610
        monitor->MainPos = main_viewport->Pos;
13611
        monitor->MainSize = main_viewport->Size;
13612
        monitor->WorkPos = main_viewport->WorkPos;
13613
        monitor->WorkSize = main_viewport->WorkSize;
13614
        monitor->DpiScale = main_viewport->DpiScale;
13615
    }
13616
13617
    if (!viewports_enabled)
13618
    {
13619
        g.MouseViewport = main_viewport;
13620
        return;
13621
    }
13622
13623
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
13624
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
13625
    ImGuiViewportP* viewport_hovered = NULL;
13626
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
13627
    {
13628
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
13629
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
13630
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
13631
    }
13632
    else
13633
    {
13634
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
13635
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
13636
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
13637
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
13638
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
13639
    }
13640
    if (viewport_hovered != NULL)
13641
        g.MouseLastHoveredViewport = viewport_hovered;
13642
    else if (g.MouseLastHoveredViewport == NULL)
13643
        g.MouseLastHoveredViewport = g.Viewports[0];
13644
13645
    // Update mouse reference viewport
13646
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
13647
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
13648
    if (g.MovingWindow && g.MovingWindow->Viewport)
13649
        g.MouseViewport = g.MovingWindow->Viewport;
13650
    else
13651
        g.MouseViewport = g.MouseLastHoveredViewport;
13652
13653
    // When dragging something, always refer to the last hovered viewport.
13654
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
13655
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
13656
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
13657
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
13658
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
13659
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
13660
        viewport_hovered = g.MouseLastHoveredViewport;
13661
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
13662
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
13663
            g.MouseViewport = viewport_hovered;
13664
13665
    IM_ASSERT(g.MouseViewport != NULL);
13666
}
13667
13668
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
13669
static void ImGui::UpdateViewportsEndFrame()
13670
{
13671
    ImGuiContext& g = *GImGui;
13672
    g.PlatformIO.Viewports.resize(0);
13673
    for (int i = 0; i < g.Viewports.Size; i++)
13674
    {
13675
        ImGuiViewportP* viewport = g.Viewports[i];
13676
        viewport->LastPos = viewport->Pos;
13677
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
13678
            if (i > 0) // Always include main viewport in the list
13679
                continue;
13680
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
13681
            continue;
13682
        if (i > 0)
13683
            IM_ASSERT(viewport->Window != NULL);
13684
        g.PlatformIO.Viewports.push_back(viewport);
13685
    }
13686
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
13687
}
13688
13689
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
13690
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
13691
{
13692
    ImGuiContext& g = *GImGui;
13693
    IM_ASSERT(id != 0);
13694
13695
    flags |= ImGuiViewportFlags_IsPlatformWindow;
13696
    if (window != NULL)
13697
    {
13698
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
13699
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
13700
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
13701
            flags |= ImGuiViewportFlags_NoInputs;
13702
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
13703
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
13704
    }
13705
13706
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
13707
    if (viewport)
13708
    {
13709
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
13710
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
13711
            viewport->Pos = pos;
13712
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
13713
            viewport->Size = size;
13714
        viewport->Flags = flags | (viewport->Flags & ImGuiViewportFlags_Minimized); // Preserve existing flags
13715
    }
13716
    else
13717
    {
13718
        // New viewport
13719
        viewport = IM_NEW(ImGuiViewportP)();
13720
        viewport->ID = id;
13721
        viewport->Idx = g.Viewports.Size;
13722
        viewport->Pos = viewport->LastPos = pos;
13723
        viewport->Size = size;
13724
        viewport->Flags = flags;
13725
        UpdateViewportPlatformMonitor(viewport);
13726
        g.Viewports.push_back(viewport);
13727
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
13728
13729
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
13730
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
13731
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
13732
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
13733
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
13734
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
13735
13736
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
13737
        // This is so we can select an appropriate font size on the first frame of our window lifetime
13738
        if (viewport->PlatformMonitor != -1)
13739
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
13740
    }
13741
13742
    viewport->Window = window;
13743
    viewport->LastFrameActive = g.FrameCount;
13744
    viewport->UpdateWorkRect();
13745
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
13746
13747
    if (window != NULL)
13748
        window->ViewportOwned = true;
13749
13750
    return viewport;
13751
}
13752
13753
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
13754
{
13755
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
13756
    ImGuiContext& g = *GImGui;
13757
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
13758
    {
13759
        ImGuiWindow* window = g.Windows[window_n];
13760
        if (window->Viewport != viewport)
13761
            continue;
13762
        window->Viewport = NULL;
13763
        window->ViewportOwned = false;
13764
    }
13765
    if (viewport == g.MouseLastHoveredViewport)
13766
        g.MouseLastHoveredViewport = NULL;
13767
13768
    // Destroy
13769
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
13770
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
13771
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
13772
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
13773
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
13774
    IM_DELETE(viewport);
13775
}
13776
13777
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
13778
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
13779
{
13780
    ImGuiContext& g = *GImGui;
13781
    ImGuiWindowFlags flags = window->Flags;
13782
    window->ViewportAllowPlatformMonitorExtend = -1;
13783
13784
    // Restore main viewport if multi-viewport is not supported by the backend
13785
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
13786
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
13787
    {
13788
        SetWindowViewport(window, main_viewport);
13789
        return;
13790
    }
13791
    window->ViewportOwned = false;
13792
13793
    // Appearing popups reset their viewport so they can inherit again
13794
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
13795
    {
13796
        window->Viewport = NULL;
13797
        window->ViewportId = 0;
13798
    }
13799
13800
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
13801
    {
13802
        // By default inherit from parent window
13803
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
13804
            window->Viewport = window->ParentWindow->Viewport;
13805
13806
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
13807
        if (window->Viewport == NULL && window->ViewportId != 0)
13808
        {
13809
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
13810
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
13811
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
13812
        }
13813
    }
13814
13815
    bool lock_viewport = false;
13816
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
13817
    {
13818
        // Code explicitly request a viewport
13819
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
13820
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
13821
        lock_viewport = true;
13822
    }
13823
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
13824
    {
13825
        // Always inherit viewport from parent window
13826
        if (window->DockNode && window->DockNode->HostWindow)
13827
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
13828
        window->Viewport = window->ParentWindow->Viewport;
13829
    }
13830
    else if (window->DockNode && window->DockNode->HostWindow)
13831
    {
13832
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
13833
        window->Viewport = window->DockNode->HostWindow->Viewport;
13834
    }
13835
    else if (flags & ImGuiWindowFlags_Tooltip)
13836
    {
13837
        window->Viewport = g.MouseViewport;
13838
    }
13839
    else if (GetWindowAlwaysWantOwnViewport(window))
13840
    {
13841
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
13842
    }
13843
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
13844
    {
13845
        if (window->Viewport != NULL && window->Viewport->Window == window)
13846
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
13847
    }
13848
    else
13849
    {
13850
        // Merge into host viewport?
13851
        // We cannot test window->ViewportOwned as it set lower in the function.
13852
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
13853
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
13854
        if (try_to_merge_into_host_viewport)
13855
            UpdateTryMergeWindowIntoHostViewports(window);
13856
    }
13857
13858
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
13859
    if (window->Viewport == NULL)
13860
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
13861
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
13862
13863
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
13864
    if (!lock_viewport)
13865
    {
13866
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
13867
        {
13868
            // We need to take account of the possibility that mouse may become invalid.
13869
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
13870
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
13871
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
13872
            bool mouse_valid = IsMousePosValid(&mouse_ref);
13873
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
13874
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
13875
            else
13876
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
13877
        }
13878
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
13879
        {
13880
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
13881
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
13882
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
13883
            {
13884
                // Steal/transfer ownership
13885
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
13886
                window->Viewport->Window = window;
13887
                window->Viewport->ID = window->ID;
13888
                window->Viewport->LastNameHash = 0;
13889
            }
13890
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
13891
            {
13892
                // New viewport
13893
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
13894
            }
13895
        }
13896
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
13897
        {
13898
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
13899
            // Child windows are kept contained within their parent.
13900
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
13901
        }
13902
    }
13903
13904
    // Update flags
13905
    window->ViewportOwned = (window == window->Viewport->Window);
13906
    window->ViewportId = window->Viewport->ID;
13907
13908
    // If the OS window has a title bar, hide our imgui title bar
13909
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
13910
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
13911
}
13912
13913
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
13914
{
13915
    ImGuiContext& g = *GImGui;
13916
13917
    bool viewport_rect_changed = false;
13918
13919
    // Synchronize window --> viewport in most situations
13920
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
13921
    if (window->Viewport->PlatformRequestMove)
13922
    {
13923
        window->Pos = window->Viewport->Pos;
13924
        MarkIniSettingsDirty(window);
13925
    }
13926
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
13927
    {
13928
        viewport_rect_changed = true;
13929
        window->Viewport->Pos = window->Pos;
13930
    }
13931
13932
    if (window->Viewport->PlatformRequestResize)
13933
    {
13934
        window->Size = window->SizeFull = window->Viewport->Size;
13935
        MarkIniSettingsDirty(window);
13936
    }
13937
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
13938
    {
13939
        viewport_rect_changed = true;
13940
        window->Viewport->Size = window->Size;
13941
    }
13942
    window->Viewport->UpdateWorkRect();
13943
13944
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
13945
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
13946
    if (viewport_rect_changed)
13947
        UpdateViewportPlatformMonitor(window->Viewport);
13948
13949
    // Update common viewport flags
13950
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
13951
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
13952
    ImGuiWindowFlags window_flags = window->Flags;
13953
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
13954
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
13955
    if (window_flags & ImGuiWindowFlags_Tooltip)
13956
        viewport_flags |= ImGuiViewportFlags_TopMost;
13957
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
13958
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
13959
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
13960
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
13961
13962
    // Not correct to set modal as topmost because:
13963
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
13964
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
13965
    //if (flags & ImGuiWindowFlags_Modal)
13966
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
13967
13968
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
13969
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
13970
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
13971
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
13972
    if (is_short_lived_floating_window && !is_modal)
13973
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
13974
13975
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
13976
    if (window->WindowClass.ViewportFlagsOverrideSet)
13977
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
13978
    if (window->WindowClass.ViewportFlagsOverrideClear)
13979
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
13980
13981
    // We can also tell the backend that clearing the platform window won't be necessary,
13982
    // as our window background is filling the viewport and we have disabled BgAlpha.
13983
    // FIXME: Work on support for per-viewport transparency (#2766)
13984
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
13985
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
13986
13987
    window->Viewport->Flags = viewport_flags;
13988
13989
    // Update parent viewport ID
13990
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
13991
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
13992
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
13993
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
13994
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
13995
    else
13996
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
13997
}
13998
13999
// Called by user at the end of the main loop, after EndFrame()
14000
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
14001
void ImGui::UpdatePlatformWindows()
14002
{
14003
    ImGuiContext& g = *GImGui;
14004
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
14005
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
14006
    g.FrameCountPlatformEnded = g.FrameCount;
14007
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14008
        return;
14009
14010
    // Create/resize/destroy platform windows to match each active viewport.
14011
    // Skip the main viewport (index 0), which is always fully handled by the application!
14012
    for (int i = 1; i < g.Viewports.Size; i++)
14013
    {
14014
        ImGuiViewportP* viewport = g.Viewports[i];
14015
14016
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
14017
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
14018
        bool destroy_platform_window = false;
14019
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
14020
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
14021
        if (destroy_platform_window)
14022
        {
14023
            DestroyPlatformWindow(viewport);
14024
            continue;
14025
        }
14026
14027
        // New windows that appears directly in a new viewport won't always have a size on their first frame
14028
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
14029
            continue;
14030
14031
        // Create window
14032
        bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
14033
        if (is_new_platform_window)
14034
        {
14035
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14036
            g.PlatformIO.Platform_CreateWindow(viewport);
14037
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
14038
                g.PlatformIO.Renderer_CreateWindow(viewport);
14039
            viewport->LastNameHash = 0;
14040
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
14041
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
14042
            viewport->PlatformWindowCreated = true;
14043
        }
14044
14045
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
14046
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
14047
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
14048
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
14049
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
14050
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
14051
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
14052
        viewport->LastPlatformPos = viewport->Pos;
14053
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
14054
14055
        // Update title bar (if it changed)
14056
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
14057
        {
14058
            const char* title_begin = window_for_title->Name;
14059
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
14060
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
14061
            if (viewport->LastNameHash != title_hash)
14062
            {
14063
                char title_end_backup_c = *title_end;
14064
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
14065
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
14066
                *title_end = title_end_backup_c;
14067
                viewport->LastNameHash = title_hash;
14068
            }
14069
        }
14070
14071
        // Update alpha (if it changed)
14072
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
14073
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
14074
        viewport->LastAlpha = viewport->Alpha;
14075
14076
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
14077
        if (g.PlatformIO.Platform_UpdateWindow)
14078
            g.PlatformIO.Platform_UpdateWindow(viewport);
14079
14080
        if (is_new_platform_window)
14081
        {
14082
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
14083
            if (g.FrameCount < 3)
14084
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14085
14086
            // Show window
14087
            g.PlatformIO.Platform_ShowWindow(viewport);
14088
14089
            // Even without focus, we assume the window becomes front-most.
14090
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
14091
            if (viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
14092
                viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
14093
            }
14094
14095
        // Clear request flags
14096
        viewport->ClearRequestFlags();
14097
    }
14098
14099
    // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14100
    // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14101
    // FIXME-VIEWPORT: We should use this information to also set dear imgui-side focus, allowing us to handle os-level alt+tab.
14102
    if (g.PlatformIO.Platform_GetWindowFocus != NULL)
14103
    {
14104
        ImGuiViewportP* focused_viewport = NULL;
14105
        for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++)
14106
        {
14107
            ImGuiViewportP* viewport = g.Viewports[n];
14108
            if (viewport->PlatformWindowCreated)
14109
                if (g.PlatformIO.Platform_GetWindowFocus(viewport))
14110
                    focused_viewport = viewport;
14111
        }
14112
14113
        // Store a tag so we can infer z-order easily from all our windows
14114
        // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14115
        // will keep the front most stamp instead of losing it back to their parent viewport.
14116
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14117
        {
14118
            if (focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
14119
                focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
14120
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14121
        }
14122
    }
14123
}
14124
14125
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
14126
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
14127
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
14128
//
14129
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14130
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14131
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14132
//            MyRenderFunction(platform_io.Viewports[i], my_args);
14133
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14134
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14135
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
14136
//
14137
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
14138
{
14139
    // Skip the main viewport (index 0), which is always fully handled by the application!
14140
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14141
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14142
    {
14143
        ImGuiViewport* viewport = platform_io.Viewports[i];
14144
        if (viewport->Flags & ImGuiViewportFlags_Minimized)
14145
            continue;
14146
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
14147
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
14148
    }
14149
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14150
    {
14151
        ImGuiViewport* viewport = platform_io.Viewports[i];
14152
        if (viewport->Flags & ImGuiViewportFlags_Minimized)
14153
            continue;
14154
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
14155
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
14156
    }
14157
}
14158
14159
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
14160
{
14161
    ImGuiContext& g = *GImGui;
14162
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
14163
    {
14164
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14165
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
14166
            return monitor_n;
14167
    }
14168
    return -1;
14169
}
14170
14171
// Search for the monitor with the largest intersection area with the given rectangle
14172
// We generally try to avoid searching loops but the monitor count should be very small here
14173
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
14174
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
14175
{
14176
    ImGuiContext& g = *GImGui;
14177
14178
    const int monitor_count = g.PlatformIO.Monitors.Size;
14179
    if (monitor_count <= 1)
14180
        return monitor_count - 1;
14181
14182
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
14183
    // This is necessary for tooltips which always resize down to zero at first.
14184
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
14185
    int best_monitor_n = -1;
14186
    float best_monitor_surface = 0.001f;
14187
14188
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
14189
    {
14190
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14191
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
14192
        if (monitor_rect.Contains(rect))
14193
            return monitor_n;
14194
        ImRect overlapping_rect = rect;
14195
        overlapping_rect.ClipWithFull(monitor_rect);
14196
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
14197
        if (overlapping_surface < best_monitor_surface)
14198
            continue;
14199
        best_monitor_surface = overlapping_surface;
14200
        best_monitor_n = monitor_n;
14201
    }
14202
    return best_monitor_n;
14203
}
14204
14205
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
14206
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
14207
{
14208
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
14209
}
14210
14211
// Return value is always != NULL, but don't hold on it across frames.
14212
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
14213
{
14214
    ImGuiContext& g = *GImGui;
14215
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
14216
    int monitor_idx = viewport->PlatformMonitor;
14217
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
14218
        return &g.PlatformIO.Monitors[monitor_idx];
14219
    return &g.FallbackMonitor;
14220
}
14221
14222
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
14223
{
14224
    ImGuiContext& g = *GImGui;
14225
    if (viewport->PlatformWindowCreated)
14226
    {
14227
        if (g.PlatformIO.Renderer_DestroyWindow)
14228
            g.PlatformIO.Renderer_DestroyWindow(viewport);
14229
        if (g.PlatformIO.Platform_DestroyWindow)
14230
            g.PlatformIO.Platform_DestroyWindow(viewport);
14231
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
14232
14233
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
14234
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
14235
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
14236
            viewport->PlatformWindowCreated = false;
14237
    }
14238
    else
14239
    {
14240
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
14241
    }
14242
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
14243
    viewport->ClearRequestFlags();
14244
}
14245
14246
void ImGui::DestroyPlatformWindows()
14247
{
14248
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
14249
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
14250
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
14251
    // code to operator a consistent manner.
14252
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
14253
    // crashing if it doesn't have data stored.
14254
    ImGuiContext& g = *GImGui;
14255
    for (int i = 0; i < g.Viewports.Size; i++)
14256
        DestroyPlatformWindow(g.Viewports[i]);
14257
}
14258
14259
14260
//-----------------------------------------------------------------------------
14261
// [SECTION] DOCKING
14262
//-----------------------------------------------------------------------------
14263
// Docking: Internal Types
14264
// Docking: Forward Declarations
14265
// Docking: ImGuiDockContext
14266
// Docking: ImGuiDockContext Docking/Undocking functions
14267
// Docking: ImGuiDockNode
14268
// Docking: ImGuiDockNode Tree manipulation functions
14269
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
14270
// Docking: Builder Functions
14271
// Docking: Begin/End Support Functions (called from Begin/End)
14272
// Docking: Settings
14273
//-----------------------------------------------------------------------------
14274
14275
//-----------------------------------------------------------------------------
14276
// Typical Docking call flow: (root level is generally public API):
14277
//-----------------------------------------------------------------------------
14278
// - NewFrame()                               new dear imgui frame
14279
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
14280
//    | - DockContextProcessUndockWindow()    - process one window undocking request
14281
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
14282
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
14283
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
14284
//    | - DockContextProcessDock()            - process one docking request
14285
//    | - DockNodeUpdate()
14286
//    |   - DockNodeUpdateForRootNode()
14287
//    |     - DockNodeUpdateFlagsAndCollapse()
14288
//    |     - DockNodeFindInfo()
14289
//    |   - destroy unused node or tab bar
14290
//    |   - create dock node host window
14291
//    |      - Begin() etc.
14292
//    |   - DockNodeStartMouseMovingWindow()
14293
//    |   - DockNodeTreeUpdatePosSize()
14294
//    |   - DockNodeTreeUpdateSplitter()
14295
//    |   - draw node background
14296
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
14297
//    |     - DockNodeAddTabBar()
14298
//    |     - DockNodeUpdateWindowMenu()
14299
//    |     - DockNodeCalcTabBarLayout()
14300
//    |     - BeginTabBarEx()
14301
//    |     - TabItemEx() calls
14302
//    |     - EndTabBar()
14303
//    |   - BeginDockableDragDropTarget()
14304
//    |      - DockNodeUpdate()               - recurse into child nodes...
14305
//-----------------------------------------------------------------------------
14306
// - DockSpace()                              user submit a dockspace into a window
14307
//    | Begin(Child)                          - create a child window
14308
//    | DockNodeUpdate()                      - call main dock node update function
14309
//    | End(Child)
14310
//    | ItemSize()
14311
//-----------------------------------------------------------------------------
14312
// - Begin()
14313
//    | BeginDocked()
14314
//    | BeginDockableDragDropSource()
14315
//    | BeginDockableDragDropTarget()
14316
//    | - DockNodePreviewDockRender()
14317
//-----------------------------------------------------------------------------
14318
// - EndFrame()
14319
//    | DockContextEndFrame()
14320
//-----------------------------------------------------------------------------
14321
14322
//-----------------------------------------------------------------------------
14323
// Docking: Internal Types
14324
//-----------------------------------------------------------------------------
14325
// - ImGuiDockRequestType
14326
// - ImGuiDockRequest
14327
// - ImGuiDockPreviewData
14328
// - ImGuiDockNodeSettings
14329
// - ImGuiDockContext
14330
//-----------------------------------------------------------------------------
14331
14332
enum ImGuiDockRequestType
14333
{
14334
    ImGuiDockRequestType_None = 0,
14335
    ImGuiDockRequestType_Dock,
14336
    ImGuiDockRequestType_Undock,
14337
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
14338
};
14339
14340
struct ImGuiDockRequest
14341
{
14342
    ImGuiDockRequestType    Type;
14343
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
14344
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
14345
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
14346
    ImGuiDir                DockSplitDir;
14347
    float                   DockSplitRatio;
14348
    bool                    DockSplitOuter;
14349
    ImGuiWindow*            UndockTargetWindow;
14350
    ImGuiDockNode*          UndockTargetNode;
14351
14352
    ImGuiDockRequest()
14353
    {
14354
        Type = ImGuiDockRequestType_None;
14355
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
14356
        DockTargetNode = UndockTargetNode = NULL;
14357
        DockSplitDir = ImGuiDir_None;
14358
        DockSplitRatio = 0.5f;
14359
        DockSplitOuter = false;
14360
    }
14361
};
14362
14363
struct ImGuiDockPreviewData
14364
{
14365
    ImGuiDockNode   FutureNode;
14366
    bool            IsDropAllowed;
14367
    bool            IsCenterAvailable;
14368
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
14369
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
14370
    ImGuiDockNode*  SplitNode;
14371
    ImGuiDir        SplitDir;
14372
    float           SplitRatio;
14373
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
14374
14375
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
14376
};
14377
14378
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
14379
struct ImGuiDockNodeSettings
14380
{
14381
    ImGuiID             ID;
14382
    ImGuiID             ParentNodeId;
14383
    ImGuiID             ParentWindowId;
14384
    ImGuiID             SelectedTabId;
14385
    signed char         SplitAxis;
14386
    char                Depth;
14387
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
14388
    ImVec2ih            Pos;
14389
    ImVec2ih            Size;
14390
    ImVec2ih            SizeRef;
14391
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
14392
};
14393
14394
//-----------------------------------------------------------------------------
14395
// Docking: Forward Declarations
14396
//-----------------------------------------------------------------------------
14397
14398
namespace ImGui
14399
{
14400
    // ImGuiDockContext
14401
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
14402
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
14403
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
14404
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
14405
    static void             DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref = true);
14406
    static void             DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node);
14407
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
14408
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
14409
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
14410
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
14411
14412
    // ImGuiDockNode
14413
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
14414
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14415
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14416
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
14417
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
14418
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
14419
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
14420
    static void             DockNodeUpdate(ImGuiDockNode* node);
14421
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
14422
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
14423
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
14424
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
14425
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
14426
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
14427
    static ImGuiID          DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
14428
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
14429
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
14430
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
14431
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
14432
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
14433
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
14434
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
14435
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
14436
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
14437
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
14438
14439
    // ImGuiDockNode tree manipulations
14440
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
14441
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
14442
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
14443
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
14444
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
14445
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
14446
14447
    // Settings
14448
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
14449
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
14450
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
14451
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
14452
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
14453
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
14454
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
14455
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
14456
}
14457
14458
//-----------------------------------------------------------------------------
14459
// Docking: ImGuiDockContext
14460
//-----------------------------------------------------------------------------
14461
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
14462
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
14463
// At boot time only, we run a simple GC to remove nodes that have no references.
14464
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
14465
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
14466
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
14467
//-----------------------------------------------------------------------------
14468
// - DockContextInitialize()
14469
// - DockContextShutdown()
14470
// - DockContextClearNodes()
14471
// - DockContextRebuildNodes()
14472
// - DockContextNewFrameUpdateUndocking()
14473
// - DockContextNewFrameUpdateDocking()
14474
// - DockContextEndFrame()
14475
// - DockContextFindNodeByID()
14476
// - DockContextBindNodeToWindow()
14477
// - DockContextGenNodeID()
14478
// - DockContextAddNode()
14479
// - DockContextRemoveNode()
14480
// - ImGuiDockContextPruneNodeData
14481
// - DockContextPruneUnusedSettingsNodes()
14482
// - DockContextBuildNodesFromSettings()
14483
// - DockContextBuildAddWindowsToNodes()
14484
//-----------------------------------------------------------------------------
14485
14486
void ImGui::DockContextInitialize(ImGuiContext* ctx)
14487
{
14488
    ImGuiContext& g = *ctx;
14489
14490
    // Add .ini handle for persistent docking data
14491
    ImGuiSettingsHandler ini_handler;
14492
    ini_handler.TypeName = "Docking";
14493
    ini_handler.TypeHash = ImHashStr("Docking");
14494
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
14495
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
14496
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
14497
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
14498
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
14499
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
14500
    g.SettingsHandlers.push_back(ini_handler);
14501
}
14502
14503
void ImGui::DockContextShutdown(ImGuiContext* ctx)
14504
{
14505
    ImGuiDockContext* dc  = &ctx->DockContext;
14506
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14507
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14508
            IM_DELETE(node);
14509
}
14510
14511
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
14512
{
14513
    IM_UNUSED(ctx);
14514
    IM_ASSERT(ctx == GImGui);
14515
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
14516
    DockBuilderRemoveNodeChildNodes(root_id);
14517
}
14518
14519
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
14520
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
14521
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
14522
{
14523
    ImGuiContext& g = *ctx;
14524
    ImGuiDockContext* dc = &ctx->DockContext;
14525
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
14526
    SaveIniSettingsToMemory();
14527
    ImGuiID root_id = 0; // Rebuild all
14528
    DockContextClearNodes(ctx, root_id, false);
14529
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
14530
    DockContextBuildAddWindowsToNodes(ctx, root_id);
14531
}
14532
14533
// Docking context update function, called by NewFrame()
14534
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
14535
{
14536
    ImGuiContext& g = *ctx;
14537
    ImGuiDockContext* dc = &ctx->DockContext;
14538
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
14539
    {
14540
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
14541
            DockContextClearNodes(ctx, 0, true);
14542
        return;
14543
    }
14544
14545
    // Setting NoSplit at runtime merges all nodes
14546
    if (g.IO.ConfigDockingNoSplit)
14547
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
14548
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14549
                if (node->IsRootNode() && node->IsSplitNode())
14550
                {
14551
                    DockBuilderRemoveNodeChildNodes(node->ID);
14552
                    //dc->WantFullRebuild = true;
14553
                }
14554
14555
    // Process full rebuild
14556
#if 0
14557
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
14558
        dc->WantFullRebuild = true;
14559
#endif
14560
    if (dc->WantFullRebuild)
14561
    {
14562
        DockContextRebuildNodes(ctx);
14563
        dc->WantFullRebuild = false;
14564
    }
14565
14566
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
14567
    for (int n = 0; n < dc->Requests.Size; n++)
14568
    {
14569
        ImGuiDockRequest* req = &dc->Requests[n];
14570
        if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow)
14571
            DockContextProcessUndockWindow(ctx, req->UndockTargetWindow);
14572
        else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode)
14573
            DockContextProcessUndockNode(ctx, req->UndockTargetNode);
14574
    }
14575
}
14576
14577
// Docking context update function, called by NewFrame()
14578
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
14579
{
14580
    ImGuiContext& g = *ctx;
14581
    ImGuiDockContext* dc  = &ctx->DockContext;
14582
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
14583
        return;
14584
14585
    // [DEBUG] Store hovered dock node.
14586
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
14587
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
14588
    g.DebugHoveredDockNode = NULL;
14589
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
14590
    {
14591
        if (hovered_window->DockNodeAsHost)
14592
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
14593
        else if (hovered_window->RootWindow->DockNode)
14594
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
14595
    }
14596
14597
    // Process Docking requests
14598
    for (int n = 0; n < dc->Requests.Size; n++)
14599
        if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
14600
            DockContextProcessDock(ctx, &dc->Requests[n]);
14601
    dc->Requests.resize(0);
14602
14603
    // Create windows for each automatic docking nodes
14604
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
14605
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14606
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14607
            if (node->IsFloatingNode())
14608
                DockNodeUpdate(node);
14609
}
14610
14611
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
14612
{
14613
    // Draw backgrounds of node missing their window
14614
    ImGuiContext& g = *ctx;
14615
    ImGuiDockContext* dc = &g.DockContext;
14616
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14617
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14618
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
14619
            {
14620
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
14621
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), DOCKING_SPLITTER_SIZE);
14622
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
14623
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
14624
            }
14625
}
14626
14627
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
14628
{
14629
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
14630
}
14631
14632
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
14633
{
14634
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
14635
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
14636
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
14637
    ImGuiID id = 0x0001;
14638
    while (DockContextFindNodeByID(ctx, id) != NULL)
14639
        id++;
14640
    return id;
14641
}
14642
14643
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
14644
{
14645
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
14646
    ImGuiContext& g = *ctx;
14647
    if (id == 0)
14648
        id = DockContextGenNodeID(ctx);
14649
    else
14650
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
14651
14652
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
14653
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
14654
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
14655
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
14656
    return node;
14657
}
14658
14659
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
14660
{
14661
    ImGuiContext& g = *ctx;
14662
    ImGuiDockContext* dc  = &ctx->DockContext;
14663
14664
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
14665
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
14666
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
14667
    IM_ASSERT(node->Windows.Size == 0);
14668
14669
    if (node->HostWindow)
14670
        node->HostWindow->DockNodeAsHost = NULL;
14671
14672
    ImGuiDockNode* parent_node = node->ParentNode;
14673
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
14674
    if (merge)
14675
    {
14676
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
14677
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
14678
        DockNodeTreeMerge(&g, parent_node, sibling_node);
14679
    }
14680
    else
14681
    {
14682
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
14683
            if (parent_node->ChildNodes[n] == node)
14684
                node->ParentNode->ChildNodes[n] = NULL;
14685
        dc->Nodes.SetVoidPtr(node->ID, NULL);
14686
        IM_DELETE(node);
14687
    }
14688
}
14689
14690
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
14691
{
14692
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
14693
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
14694
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
14695
}
14696
14697
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
14698
struct ImGuiDockContextPruneNodeData
14699
{
14700
    int         CountWindows, CountChildWindows, CountChildNodes;
14701
    ImGuiID     RootId;
14702
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
14703
};
14704
14705
// Garbage collect unused nodes (run once at init time)
14706
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
14707
{
14708
    ImGuiContext& g = *ctx;
14709
    ImGuiDockContext* dc  = &ctx->DockContext;
14710
    IM_ASSERT(g.Windows.Size == 0);
14711
14712
    ImPool<ImGuiDockContextPruneNodeData> pool;
14713
    pool.Reserve(dc->NodesSettings.Size);
14714
14715
    // Count child nodes and compute RootID
14716
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
14717
    {
14718
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
14719
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
14720
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
14721
        if (settings->ParentNodeId)
14722
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
14723
    }
14724
14725
    // Count reference to dock ids from dockspaces
14726
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
14727
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
14728
    {
14729
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
14730
        if (settings->ParentWindowId != 0)
14731
            if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->ParentWindowId))
14732
                if (window_settings->DockId)
14733
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
14734
                        data->CountChildNodes++;
14735
    }
14736
14737
    // Count reference to dock ids from window settings
14738
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
14739
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14740
        if (ImGuiID dock_id = settings->DockId)
14741
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
14742
            {
14743
                data->CountWindows++;
14744
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
14745
                    data_root->CountChildWindows++;
14746
            }
14747
14748
    // Prune
14749
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
14750
    {
14751
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
14752
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
14753
        if (data->CountWindows > 1)
14754
            continue;
14755
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
14756
14757
        bool remove = false;
14758
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
14759
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
14760
        remove |= (data_root->CountChildWindows == 0);
14761
        if (remove)
14762
        {
14763
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
14764
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
14765
            settings->ID = 0;
14766
        }
14767
    }
14768
}
14769
14770
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
14771
{
14772
    // Build nodes
14773
    for (int node_n = 0; node_n < node_settings_count; node_n++)
14774
    {
14775
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
14776
        if (settings->ID == 0)
14777
            continue;
14778
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
14779
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
14780
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
14781
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
14782
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
14783
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
14784
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
14785
            node->ParentNode->ChildNodes[0] = node;
14786
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
14787
            node->ParentNode->ChildNodes[1] = node;
14788
        node->SelectedTabId = settings->SelectedTabId;
14789
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
14790
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
14791
14792
        // Bind host window immediately if it already exist (in case of a rebuild)
14793
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
14794
        char host_window_title[20];
14795
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
14796
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
14797
    }
14798
}
14799
14800
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
14801
{
14802
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
14803
    ImGuiContext& g = *ctx;
14804
    for (int n = 0; n < g.Windows.Size; n++)
14805
    {
14806
        ImGuiWindow* window = g.Windows[n];
14807
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
14808
            continue;
14809
        if (window->DockNode != NULL)
14810
            continue;
14811
14812
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
14813
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
14814
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
14815
            DockNodeAddWindow(node, window, true);
14816
    }
14817
}
14818
14819
//-----------------------------------------------------------------------------
14820
// Docking: ImGuiDockContext Docking/Undocking functions
14821
//-----------------------------------------------------------------------------
14822
// - DockContextQueueDock()
14823
// - DockContextQueueUndockWindow()
14824
// - DockContextQueueUndockNode()
14825
// - DockContextQueueNotifyRemovedNode()
14826
// - DockContextProcessDock()
14827
// - DockContextProcessUndockWindow()
14828
// - DockContextProcessUndockNode()
14829
// - DockContextCalcDropPosForDocking()
14830
//-----------------------------------------------------------------------------
14831
14832
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
14833
{
14834
    IM_ASSERT(target != payload);
14835
    ImGuiDockRequest req;
14836
    req.Type = ImGuiDockRequestType_Dock;
14837
    req.DockTargetWindow = target;
14838
    req.DockTargetNode = target_node;
14839
    req.DockPayload = payload;
14840
    req.DockSplitDir = split_dir;
14841
    req.DockSplitRatio = split_ratio;
14842
    req.DockSplitOuter = split_outer;
14843
    ctx->DockContext.Requests.push_back(req);
14844
}
14845
14846
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
14847
{
14848
    ImGuiDockRequest req;
14849
    req.Type = ImGuiDockRequestType_Undock;
14850
    req.UndockTargetWindow = window;
14851
    ctx->DockContext.Requests.push_back(req);
14852
}
14853
14854
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
14855
{
14856
    ImGuiDockRequest req;
14857
    req.Type = ImGuiDockRequestType_Undock;
14858
    req.UndockTargetNode = node;
14859
    ctx->DockContext.Requests.push_back(req);
14860
}
14861
14862
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
14863
{
14864
    ImGuiDockContext* dc  = &ctx->DockContext;
14865
    for (int n = 0; n < dc->Requests.Size; n++)
14866
        if (dc->Requests[n].DockTargetNode == node)
14867
            dc->Requests[n].Type = ImGuiDockRequestType_None;
14868
}
14869
14870
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
14871
{
14872
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
14873
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
14874
14875
    ImGuiContext& g = *ctx;
14876
    IM_UNUSED(g);
14877
14878
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
14879
    ImGuiWindow* target_window = req->DockTargetWindow;
14880
    ImGuiDockNode* node = req->DockTargetNode;
14881
    if (payload_window)
14882
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
14883
    else
14884
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
14885
14886
    // Decide which Tab will be selected at the end of the operation
14887
    ImGuiID next_selected_id = 0;
14888
    ImGuiDockNode* payload_node = NULL;
14889
    if (payload_window)
14890
    {
14891
        payload_node = payload_window->DockNodeAsHost;
14892
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
14893
        if (payload_node && payload_node->IsLeafNode())
14894
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
14895
        if (payload_node == NULL)
14896
            next_selected_id = payload_window->TabId;
14897
    }
14898
14899
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
14900
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
14901
    if (node)
14902
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
14903
    if (node && target_window && node == target_window->DockNodeAsHost)
14904
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
14905
14906
    // Create new node and add existing window to it
14907
    if (node == NULL)
14908
    {
14909
        node = DockContextAddNode(ctx, 0);
14910
        node->Pos = target_window->Pos;
14911
        node->Size = target_window->Size;
14912
        if (target_window->DockNodeAsHost == NULL)
14913
        {
14914
            DockNodeAddWindow(node, target_window, true);
14915
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
14916
            target_window->DockIsActive = true;
14917
        }
14918
    }
14919
14920
    ImGuiDir split_dir = req->DockSplitDir;
14921
    if (split_dir != ImGuiDir_None)
14922
    {
14923
        // Split into two, one side will be our payload node unless we are dropping a loose window
14924
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
14925
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
14926
        const float split_ratio = req->DockSplitRatio;
14927
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
14928
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
14929
        new_node->HostWindow = node->HostWindow;
14930
        node = new_node;
14931
    }
14932
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
14933
14934
    if (node != payload_node)
14935
    {
14936
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
14937
        if (node->Windows.Size > 0 && node->TabBar == NULL)
14938
        {
14939
            DockNodeAddTabBar(node);
14940
            for (int n = 0; n < node->Windows.Size; n++)
14941
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
14942
        }
14943
14944
        if (payload_node != NULL)
14945
        {
14946
            // Transfer full payload node (with 1+ child windows or child nodes)
14947
            if (payload_node->IsSplitNode())
14948
            {
14949
                if (node->Windows.Size > 0)
14950
                {
14951
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
14952
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
14953
                    // This allows us to preserve some of the underlying dock tree settings nicely.
14954
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
14955
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
14956
                    if (visible_node->TabBar)
14957
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
14958
                    DockNodeMoveWindows(node, visible_node);
14959
                    DockNodeMoveWindows(visible_node, node);
14960
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
14961
                }
14962
                if (node->IsCentralNode())
14963
                {
14964
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
14965
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
14966
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
14967
                    IM_ASSERT(last_focused_node != NULL);
14968
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
14969
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
14970
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
14971
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
14972
                    last_focused_root_node->CentralNode = last_focused_node;
14973
                }
14974
14975
                IM_ASSERT(node->Windows.Size == 0);
14976
                DockNodeMoveChildNodes(node, payload_node);
14977
            }
14978
            else
14979
            {
14980
                const ImGuiID payload_dock_id = payload_node->ID;
14981
                DockNodeMoveWindows(node, payload_node);
14982
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
14983
            }
14984
            DockContextRemoveNode(ctx, payload_node, true);
14985
        }
14986
        else if (payload_window)
14987
        {
14988
            // Transfer single window
14989
            const ImGuiID payload_dock_id = payload_window->DockId;
14990
            node->VisibleWindow = payload_window;
14991
            DockNodeAddWindow(node, payload_window, true);
14992
            if (payload_dock_id != 0)
14993
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
14994
        }
14995
    }
14996
    else
14997
    {
14998
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
14999
        node->WantHiddenTabBarUpdate = true;
15000
    }
15001
15002
    // Update selection immediately
15003
    if (ImGuiTabBar* tab_bar = node->TabBar)
15004
        tab_bar->NextSelectedTabId = next_selected_id;
15005
    MarkIniSettingsDirty();
15006
}
15007
15008
// Problem:
15009
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
15010
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
15011
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
15012
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
15013
// Solution:
15014
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
15015
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
15016
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
15017
{
15018
    if (ref_viewport == NULL)
15019
        return size;
15020
15021
    ImGuiContext& g = *GImGui;
15022
    ImVec2 max_size = ImFloor(ref_viewport->WorkSize * 0.90f);
15023
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15024
    {
15025
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
15026
        max_size = ImFloor(monitor->WorkSize * 0.90f);
15027
    }
15028
    return ImMin(size, max_size);
15029
}
15030
15031
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
15032
{
15033
    ImGuiContext& g = *ctx;
15034
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
15035
    if (window->DockNode)
15036
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
15037
    else
15038
        window->DockId = 0;
15039
    window->Collapsed = false;
15040
    window->DockIsActive = false;
15041
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
15042
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
15043
15044
    MarkIniSettingsDirty();
15045
}
15046
15047
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15048
{
15049
    ImGuiContext& g = *ctx;
15050
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
15051
    IM_ASSERT(node->IsLeafNode());
15052
    IM_ASSERT(node->Windows.Size >= 1);
15053
15054
    if (node->IsRootNode() || node->IsCentralNode())
15055
    {
15056
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
15057
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
15058
        new_node->Pos = node->Pos;
15059
        new_node->Size = node->Size;
15060
        new_node->SizeRef = node->SizeRef;
15061
        DockNodeMoveWindows(new_node, node);
15062
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
15063
        node = new_node;
15064
    }
15065
    else
15066
    {
15067
        // Otherwise extract our node and merge our sibling back into the parent node.
15068
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15069
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
15070
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
15071
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
15072
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
15073
        node->ParentNode = NULL;
15074
    }
15075
    for (int n = 0; n < node->Windows.Size; n++)
15076
    {
15077
        ImGuiWindow* window = node->Windows[n];
15078
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15079
        if (window->ParentWindow)
15080
            window->ParentWindow->DC.ChildWindows.find_erase(window);
15081
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
15082
    }
15083
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
15084
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
15085
    node->WantMouseMove = true;
15086
    MarkIniSettingsDirty();
15087
}
15088
15089
// This is mostly used for automation.
15090
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
15091
{
15092
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
15093
    // (which would be functionally identical) we only show the outer one. Reflect this here.
15094
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
15095
        split_outer = true;
15096
    ImGuiDockPreviewData split_data;
15097
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
15098
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
15099
        return false;
15100
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
15101
    return true;
15102
}
15103
15104
//-----------------------------------------------------------------------------
15105
// Docking: ImGuiDockNode
15106
//-----------------------------------------------------------------------------
15107
// - DockNodeGetTabOrder()
15108
// - DockNodeAddWindow()
15109
// - DockNodeRemoveWindow()
15110
// - DockNodeMoveChildNodes()
15111
// - DockNodeMoveWindows()
15112
// - DockNodeApplyPosSizeToWindows()
15113
// - DockNodeHideHostWindow()
15114
// - ImGuiDockNodeFindInfoResults
15115
// - DockNodeFindInfo()
15116
// - DockNodeFindWindowByID()
15117
// - DockNodeUpdateFlagsAndCollapse()
15118
// - DockNodeUpdateHasCentralNodeFlag()
15119
// - DockNodeUpdateVisibleFlag()
15120
// - DockNodeStartMouseMovingWindow()
15121
// - DockNodeUpdate()
15122
// - DockNodeUpdateWindowMenu()
15123
// - DockNodeBeginAmendTabBar()
15124
// - DockNodeEndAmendTabBar()
15125
// - DockNodeUpdateTabBar()
15126
// - DockNodeAddTabBar()
15127
// - DockNodeRemoveTabBar()
15128
// - DockNodeIsDropAllowedOne()
15129
// - DockNodeIsDropAllowed()
15130
// - DockNodeCalcTabBarLayout()
15131
// - DockNodeCalcSplitRects()
15132
// - DockNodeCalcDropRectsAndTestMousePos()
15133
// - DockNodePreviewDockSetup()
15134
// - DockNodePreviewDockRender()
15135
//-----------------------------------------------------------------------------
15136
15137
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
15138
{
15139
    ID = id;
15140
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
15141
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
15142
    TabBar = NULL;
15143
    SplitAxis = ImGuiAxis_None;
15144
15145
    State = ImGuiDockNodeState_Unknown;
15146
    LastBgColor = IM_COL32_WHITE;
15147
    HostWindow = VisibleWindow = NULL;
15148
    CentralNode = OnlyNodeWithWindows = NULL;
15149
    CountNodeWithWindows = 0;
15150
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
15151
    LastFocusedNodeId = 0;
15152
    SelectedTabId = 0;
15153
    WantCloseTabId = 0;
15154
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
15155
    AuthorityForViewport = ImGuiDataAuthority_Auto;
15156
    IsVisible = true;
15157
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
15158
    IsBgDrawnThisFrame = false;
15159
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
15160
}
15161
15162
ImGuiDockNode::~ImGuiDockNode()
15163
{
15164
    IM_DELETE(TabBar);
15165
    TabBar = NULL;
15166
    ChildNodes[0] = ChildNodes[1] = NULL;
15167
}
15168
15169
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
15170
{
15171
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
15172
    if (tab_bar == NULL)
15173
        return -1;
15174
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
15175
    return tab ? tab_bar->GetTabOrder(tab) : -1;
15176
}
15177
15178
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
15179
{
15180
    window->Hidden = true;
15181
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
15182
}
15183
15184
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
15185
{
15186
    ImGuiContext& g = *GImGui; (void)g;
15187
    if (window->DockNode)
15188
    {
15189
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
15190
        IM_ASSERT(window->DockNode->ID != node->ID);
15191
        DockNodeRemoveWindow(window->DockNode, window, 0);
15192
    }
15193
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
15194
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15195
15196
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
15197
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
15198
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
15199
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
15200
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
15201
15202
    node->Windows.push_back(window);
15203
    node->WantHiddenTabBarUpdate = true;
15204
    window->DockNode = node;
15205
    window->DockId = node->ID;
15206
    window->DockIsActive = (node->Windows.Size > 1);
15207
    window->DockTabWantClose = false;
15208
15209
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
15210
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
15211
    if (node->HostWindow == NULL && node->IsFloatingNode())
15212
    {
15213
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
15214
            node->AuthorityForPos = ImGuiDataAuthority_Window;
15215
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
15216
            node->AuthorityForSize = ImGuiDataAuthority_Window;
15217
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
15218
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
15219
    }
15220
15221
    // Add to tab bar if requested
15222
    if (add_to_tab_bar)
15223
    {
15224
        if (node->TabBar == NULL)
15225
        {
15226
            DockNodeAddTabBar(node);
15227
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
15228
15229
            // Add existing windows
15230
            for (int n = 0; n < node->Windows.Size - 1; n++)
15231
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15232
        }
15233
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
15234
    }
15235
15236
    DockNodeUpdateVisibleFlag(node);
15237
15238
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
15239
    if (node->HostWindow)
15240
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
15241
}
15242
15243
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
15244
{
15245
    ImGuiContext& g = *GImGui;
15246
    IM_ASSERT(window->DockNode == node);
15247
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
15248
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
15249
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
15250
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15251
15252
    window->DockNode = NULL;
15253
    window->DockIsActive = window->DockTabWantClose = false;
15254
    window->DockId = save_dock_id;
15255
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15256
    if (window->ParentWindow)
15257
        window->ParentWindow->DC.ChildWindows.find_erase(window);
15258
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
15259
15260
    // Remove window
15261
    bool erased = false;
15262
    for (int n = 0; n < node->Windows.Size; n++)
15263
        if (node->Windows[n] == window)
15264
        {
15265
            node->Windows.erase(node->Windows.Data + n);
15266
            erased = true;
15267
            break;
15268
        }
15269
    if (!erased)
15270
        IM_ASSERT(erased);
15271
    if (node->VisibleWindow == window)
15272
        node->VisibleWindow = NULL;
15273
15274
    // Remove tab and possibly tab bar
15275
    node->WantHiddenTabBarUpdate = true;
15276
    if (node->TabBar)
15277
    {
15278
        TabBarRemoveTab(node->TabBar, window->TabId);
15279
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
15280
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
15281
            DockNodeRemoveTabBar(node);
15282
    }
15283
15284
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
15285
    {
15286
        // Automatic dock node delete themselves if they are not holding at least one tab
15287
        DockContextRemoveNode(&g, node, true);
15288
        return;
15289
    }
15290
15291
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
15292
    {
15293
        ImGuiWindow* remaining_window = node->Windows[0];
15294
        if (node->HostWindow->ViewportOwned && node->IsRootNode())
15295
        {
15296
            // Transfer viewport back to the remaining loose window
15297
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X=>%08X for Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, remaining_window->ID, remaining_window->Name);
15298
            IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow);
15299
            node->HostWindow->Viewport->Window = remaining_window;
15300
            node->HostWindow->Viewport->ID = remaining_window->ID;
15301
        }
15302
        remaining_window->Collapsed = node->HostWindow->Collapsed;
15303
    }
15304
15305
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
15306
    DockNodeUpdateVisibleFlag(node);
15307
}
15308
15309
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15310
{
15311
    IM_ASSERT(dst_node->Windows.Size == 0);
15312
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
15313
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
15314
    if (dst_node->ChildNodes[0])
15315
        dst_node->ChildNodes[0]->ParentNode = dst_node;
15316
    if (dst_node->ChildNodes[1])
15317
        dst_node->ChildNodes[1]->ParentNode = dst_node;
15318
    dst_node->SplitAxis = src_node->SplitAxis;
15319
    dst_node->SizeRef = src_node->SizeRef;
15320
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
15321
}
15322
15323
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15324
{
15325
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
15326
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
15327
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
15328
    if (src_tab_bar != NULL)
15329
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
15330
15331
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
15332
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
15333
    if (move_tab_bar)
15334
    {
15335
        dst_node->TabBar = src_node->TabBar;
15336
        src_node->TabBar = NULL;
15337
    }
15338
15339
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
15340
    for (ImGuiWindow* window : src_node->Windows)
15341
    {
15342
        window->DockNode = NULL;
15343
        window->DockIsActive = false;
15344
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
15345
    }
15346
    src_node->Windows.clear();
15347
15348
    if (!move_tab_bar && src_node->TabBar)
15349
    {
15350
        if (dst_node->TabBar)
15351
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
15352
        DockNodeRemoveTabBar(src_node);
15353
    }
15354
}
15355
15356
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
15357
{
15358
    for (int n = 0; n < node->Windows.Size; n++)
15359
    {
15360
        SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
15361
        SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always);
15362
    }
15363
}
15364
15365
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
15366
{
15367
    if (node->HostWindow)
15368
    {
15369
        if (node->HostWindow->DockNodeAsHost == node)
15370
            node->HostWindow->DockNodeAsHost = NULL;
15371
        node->HostWindow = NULL;
15372
    }
15373
15374
    if (node->Windows.Size == 1)
15375
    {
15376
        node->VisibleWindow = node->Windows[0];
15377
        node->Windows[0]->DockIsActive = false;
15378
    }
15379
15380
    if (node->TabBar)
15381
        DockNodeRemoveTabBar(node);
15382
}
15383
15384
// Search function called once by root node in DockNodeUpdate()
15385
struct ImGuiDockNodeTreeInfo
15386
{
15387
    ImGuiDockNode*      CentralNode;
15388
    ImGuiDockNode*      FirstNodeWithWindows;
15389
    int                 CountNodesWithWindows;
15390
    //ImGuiWindowClass  WindowClassForMerges;
15391
15392
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
15393
};
15394
15395
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
15396
{
15397
    if (node->Windows.Size > 0)
15398
    {
15399
        if (info->FirstNodeWithWindows == NULL)
15400
            info->FirstNodeWithWindows = node;
15401
        info->CountNodesWithWindows++;
15402
    }
15403
    if (node->IsCentralNode())
15404
    {
15405
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
15406
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
15407
        info->CentralNode = node;
15408
    }
15409
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
15410
        return;
15411
    if (node->ChildNodes[0])
15412
        DockNodeFindInfo(node->ChildNodes[0], info);
15413
    if (node->ChildNodes[1])
15414
        DockNodeFindInfo(node->ChildNodes[1], info);
15415
}
15416
15417
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
15418
{
15419
    IM_ASSERT(id != 0);
15420
    for (int n = 0; n < node->Windows.Size; n++)
15421
        if (node->Windows[n]->ID == id)
15422
            return node->Windows[n];
15423
    return NULL;
15424
}
15425
15426
// - Remove inactive windows/nodes.
15427
// - Update visibility flag.
15428
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
15429
{
15430
    ImGuiContext& g = *GImGui;
15431
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15432
15433
    // Inherit most flags
15434
    if (node->ParentNode)
15435
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
15436
15437
    // Recurse into children
15438
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
15439
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
15440
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
15441
    node->HasCentralNodeChild = false;
15442
    if (node->ChildNodes[0])
15443
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
15444
    if (node->ChildNodes[1])
15445
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
15446
15447
    // Remove inactive windows, collapse nodes
15448
    // Merge node flags overrides stored in windows
15449
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
15450
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
15451
    {
15452
        ImGuiWindow* window = node->Windows[window_n];
15453
        IM_ASSERT(window->DockNode == node);
15454
15455
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
15456
        bool remove = false;
15457
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
15458
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
15459
        remove |= (window->DockTabWantClose);
15460
        if (remove)
15461
        {
15462
            window->DockTabWantClose = false;
15463
            if (node->Windows.Size == 1 && !node->IsCentralNode())
15464
            {
15465
                DockNodeHideHostWindow(node);
15466
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
15467
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
15468
                return;
15469
            }
15470
            DockNodeRemoveWindow(node, window, node->ID);
15471
            window_n--;
15472
            continue;
15473
        }
15474
15475
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
15476
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
15477
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
15478
    }
15479
    node->UpdateMergedFlags();
15480
15481
    // Auto-hide tab bar option
15482
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
15483
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
15484
        node->WantHiddenTabBarToggle = true;
15485
    node->WantHiddenTabBarUpdate = false;
15486
15487
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
15488
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
15489
        node->WantHiddenTabBarToggle = false;
15490
15491
    // Apply toggles at a single point of the frame (here!)
15492
    if (node->Windows.Size > 1)
15493
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15494
    else if (node->WantHiddenTabBarToggle)
15495
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
15496
    node->WantHiddenTabBarToggle = false;
15497
15498
    DockNodeUpdateVisibleFlag(node);
15499
}
15500
15501
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
15502
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
15503
{
15504
    node->HasCentralNodeChild = false;
15505
    if (node->ChildNodes[0])
15506
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
15507
    if (node->ChildNodes[1])
15508
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
15509
    if (node->IsRootNode())
15510
    {
15511
        ImGuiDockNode* mark_node = node->CentralNode;
15512
        while (mark_node)
15513
        {
15514
            mark_node->HasCentralNodeChild = true;
15515
            mark_node = mark_node->ParentNode;
15516
        }
15517
    }
15518
}
15519
15520
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
15521
{
15522
    // Update visibility flag
15523
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
15524
    is_visible |= (node->Windows.Size > 0);
15525
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
15526
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
15527
    node->IsVisible = is_visible;
15528
}
15529
15530
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
15531
{
15532
    ImGuiContext& g = *GImGui;
15533
    IM_ASSERT(node->WantMouseMove == true);
15534
    StartMouseMovingWindow(window);
15535
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
15536
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
15537
    node->WantMouseMove = false;
15538
}
15539
15540
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
15541
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
15542
{
15543
    DockNodeUpdateFlagsAndCollapse(node);
15544
15545
    // - Setup central node pointers
15546
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
15547
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
15548
    ImGuiDockNodeTreeInfo info;
15549
    DockNodeFindInfo(node, &info);
15550
    node->CentralNode = info.CentralNode;
15551
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
15552
    node->CountNodeWithWindows = info.CountNodesWithWindows;
15553
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
15554
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
15555
15556
    // Copy the window class from of our first window so it can be used for proper dock filtering.
15557
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
15558
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
15559
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
15560
    {
15561
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
15562
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
15563
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
15564
            {
15565
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
15566
                break;
15567
            }
15568
    }
15569
15570
    ImGuiDockNode* mark_node = node->CentralNode;
15571
    while (mark_node)
15572
    {
15573
        mark_node->HasCentralNodeChild = true;
15574
        mark_node = mark_node->ParentNode;
15575
    }
15576
}
15577
15578
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
15579
{
15580
    // Remove ourselves from any previous different host window
15581
    // This can happen if a user mistakenly does (see #4295 for details):
15582
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
15583
    //  - N+1: NewFrame()                   // will create floating host window for that node
15584
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
15585
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
15586
        node->HostWindow->DockNodeAsHost = NULL;
15587
15588
    host_window->DockNodeAsHost = node;
15589
    node->HostWindow = host_window;
15590
}
15591
15592
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
15593
{
15594
    ImGuiContext& g = *GImGui;
15595
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
15596
    node->LastFrameAlive = g.FrameCount;
15597
    node->IsBgDrawnThisFrame = false;
15598
15599
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
15600
    if (node->IsRootNode())
15601
        DockNodeUpdateForRootNode(node);
15602
15603
    // Remove tab bar if not needed
15604
    if (node->TabBar && node->IsNoTabBar())
15605
        DockNodeRemoveTabBar(node);
15606
15607
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
15608
    bool want_to_hide_host_window = false;
15609
    if (node->IsFloatingNode())
15610
    {
15611
        if (node->Windows.Size <= 1 && node->IsLeafNode())
15612
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
15613
                want_to_hide_host_window = true;
15614
        if (node->CountNodeWithWindows == 0)
15615
            want_to_hide_host_window = true;
15616
    }
15617
    if (want_to_hide_host_window)
15618
    {
15619
        if (node->Windows.Size == 1)
15620
        {
15621
            // Floating window pos/size is authoritative
15622
            ImGuiWindow* single_window = node->Windows[0];
15623
            node->Pos = single_window->Pos;
15624
            node->Size = single_window->SizeFull;
15625
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
15626
15627
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
15628
            if (node->HostWindow && g.NavWindow == node->HostWindow)
15629
                FocusWindow(single_window);
15630
            if (node->HostWindow)
15631
            {
15632
                single_window->Viewport = node->HostWindow->Viewport;
15633
                single_window->ViewportId = node->HostWindow->ViewportId;
15634
                if (node->HostWindow->ViewportOwned)
15635
                {
15636
                    single_window->Viewport->Window = single_window;
15637
                    single_window->ViewportOwned = true;
15638
                }
15639
            }
15640
        }
15641
15642
        DockNodeHideHostWindow(node);
15643
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
15644
        node->WantCloseAll = false;
15645
        node->WantCloseTabId = 0;
15646
        node->HasCloseButton = node->HasWindowMenuButton = false;
15647
        node->LastFrameActive = g.FrameCount;
15648
15649
        if (node->WantMouseMove && node->Windows.Size == 1)
15650
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
15651
        return;
15652
    }
15653
15654
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
15655
    // while the expected visible window is resizing itself.
15656
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
15657
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
15658
    //   N+0: Begin(): window created (with no known size), node is created
15659
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
15660
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
15661
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
15662
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
15663
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
15664
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
15665
    {
15666
        IM_ASSERT(node->Windows.Size > 0);
15667
        ImGuiWindow* ref_window = NULL;
15668
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
15669
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
15670
        if (ref_window == NULL)
15671
            ref_window = node->Windows[0];
15672
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
15673
        {
15674
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
15675
            return;
15676
        }
15677
    }
15678
15679
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
15680
15681
    // Decide if the node will have a close button and a window menu button
15682
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
15683
    node->HasCloseButton = false;
15684
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
15685
    {
15686
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
15687
        ImGuiWindow* window = node->Windows[window_n];
15688
        node->HasCloseButton |= window->HasCloseButton;
15689
        window->DockIsActive = (node->Windows.Size > 1);
15690
    }
15691
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
15692
        node->HasCloseButton = false;
15693
15694
    // Bind or create host window
15695
    ImGuiWindow* host_window = NULL;
15696
    bool beginned_into_host_window = false;
15697
    if (node->IsDockSpace())
15698
    {
15699
        // [Explicit root dockspace node]
15700
        IM_ASSERT(node->HostWindow);
15701
        host_window = node->HostWindow;
15702
    }
15703
    else
15704
    {
15705
        // [Automatic root or child nodes]
15706
        if (node->IsRootNode() && node->IsVisible)
15707
        {
15708
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
15709
15710
            // Sync Pos
15711
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
15712
                SetNextWindowPos(ref_window->Pos);
15713
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
15714
                SetNextWindowPos(node->Pos);
15715
15716
            // Sync Size
15717
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
15718
                SetNextWindowSize(ref_window->SizeFull);
15719
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
15720
                SetNextWindowSize(node->Size);
15721
15722
            // Sync Collapsed
15723
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
15724
                SetNextWindowCollapsed(ref_window->Collapsed);
15725
15726
            // Sync Viewport
15727
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
15728
                SetNextWindowViewport(ref_window->ViewportId);
15729
15730
            SetNextWindowClass(&node->WindowClass);
15731
15732
            // Begin into the host window
15733
            char window_label[20];
15734
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
15735
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
15736
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
15737
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
15738
            window_flags |= ImGuiWindowFlags_NoTitleBar;
15739
15740
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
15741
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
15742
            Begin(window_label, NULL, window_flags);
15743
            PopStyleVar();
15744
            beginned_into_host_window = true;
15745
15746
            host_window = g.CurrentWindow;
15747
            DockNodeSetupHostWindow(node, host_window);
15748
            host_window->DC.CursorPos = host_window->Pos;
15749
            node->Pos = host_window->Pos;
15750
            node->Size = host_window->Size;
15751
15752
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
15753
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
15754
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
15755
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
15756
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
15757
            // after the dock host window, losing their top-most status.
15758
            if (node->HostWindow->Appearing)
15759
                BringWindowToDisplayFront(node->HostWindow);
15760
15761
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
15762
        }
15763
        else if (node->ParentNode)
15764
        {
15765
            node->HostWindow = host_window = node->ParentNode->HostWindow;
15766
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
15767
        }
15768
        if (node->WantMouseMove && node->HostWindow)
15769
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
15770
    }
15771
15772
    // Update focused node (the one whose title bar is highlight) within a node tree
15773
    if (node->IsSplitNode())
15774
        IM_ASSERT(node->TabBar == NULL);
15775
    if (node->IsRootNode())
15776
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
15777
            while (p_window != NULL && p_window->DockNode != NULL)
15778
            {
15779
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
15780
                if (p_node == node)
15781
                {
15782
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
15783
                    break;
15784
                }
15785
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
15786
            }
15787
15788
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
15789
    ImGuiDockNode* central_node = node->CentralNode;
15790
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
15791
    bool central_node_hole_register_hit_test_hole = central_node_hole;
15792
    if (central_node_hole)
15793
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
15794
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
15795
                central_node_hole_register_hit_test_hole = false;
15796
    if (central_node_hole_register_hit_test_hole)
15797
    {
15798
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
15799
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
15800
        // covering passthru node we'd have a gap on the edge not covered by the hole)
15801
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
15802
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
15803
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
15804
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
15805
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
15806
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
15807
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
15808
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
15809
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
15810
        if (central_node_hole && !hole_rect.IsInverted())
15811
        {
15812
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
15813
            if (host_window->ParentWindow)
15814
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
15815
        }
15816
    }
15817
15818
    // Update position/size, process and draw resizing splitters
15819
    if (node->IsRootNode() && host_window)
15820
    {
15821
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
15822
        DockNodeTreeUpdateSplitter(node);
15823
    }
15824
15825
    // Draw empty node background (currently can only be the Central Node)
15826
    if (host_window && node->IsEmpty() && node->IsVisible)
15827
    {
15828
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15829
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
15830
        if (node->LastBgColor != 0)
15831
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
15832
        node->IsBgDrawnThisFrame = true;
15833
    }
15834
15835
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
15836
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
15837
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
15838
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
15839
    if (render_dockspace_bg && node->IsVisible)
15840
    {
15841
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15842
        if (central_node_hole)
15843
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
15844
        else
15845
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
15846
    }
15847
15848
    // Draw and populate Tab Bar
15849
    if (host_window)
15850
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
15851
    if (host_window && node->Windows.Size > 0)
15852
    {
15853
        DockNodeUpdateTabBar(node, host_window);
15854
    }
15855
    else
15856
    {
15857
        node->WantCloseAll = false;
15858
        node->WantCloseTabId = 0;
15859
        node->IsFocused = false;
15860
    }
15861
    if (node->TabBar && node->TabBar->SelectedTabId)
15862
        node->SelectedTabId = node->TabBar->SelectedTabId;
15863
    else if (node->Windows.Size > 0)
15864
        node->SelectedTabId = node->Windows[0]->TabId;
15865
15866
    // Draw payload drop target
15867
    if (host_window && node->IsVisible)
15868
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
15869
            BeginDockableDragDropTarget(host_window);
15870
15871
    // We update this after DockNodeUpdateTabBar()
15872
    node->LastFrameActive = g.FrameCount;
15873
15874
    // Recurse into children
15875
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
15876
    if (host_window)
15877
    {
15878
        if (node->ChildNodes[0])
15879
            DockNodeUpdate(node->ChildNodes[0]);
15880
        if (node->ChildNodes[1])
15881
            DockNodeUpdate(node->ChildNodes[1]);
15882
15883
        // Render outer borders last (after the tab bar)
15884
        if (node->IsRootNode())
15885
            RenderWindowOuterBorders(host_window);
15886
    }
15887
15888
    // End host window
15889
    if (beginned_into_host_window) //-V1020
15890
        End();
15891
}
15892
15893
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
15894
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
15895
{
15896
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
15897
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
15898
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
15899
        return d;
15900
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
15901
}
15902
15903
static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
15904
{
15905
    // Try to position the menu so it is more likely to stays within the same viewport
15906
    ImGuiContext& g = *GImGui;
15907
    ImGuiID ret_tab_id = 0;
15908
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
15909
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
15910
    else
15911
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
15912
    if (BeginPopup("#WindowMenu"))
15913
    {
15914
        node->IsFocused = true;
15915
        if (tab_bar->Tabs.Size == 1)
15916
        {
15917
            if (MenuItem("Hide tab bar", NULL, node->IsHiddenTabBar()))
15918
                node->WantHiddenTabBarToggle = true;
15919
        }
15920
        else
15921
        {
15922
            for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
15923
            {
15924
                ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
15925
                if (tab->Flags & ImGuiTabItemFlags_Button)
15926
                    continue;
15927
                if (Selectable(tab_bar->GetTabName(tab), tab->ID == tab_bar->SelectedTabId))
15928
                    ret_tab_id = tab->ID;
15929
                SameLine();
15930
                Text("   ");
15931
            }
15932
        }
15933
        EndPopup();
15934
    }
15935
    return ret_tab_id;
15936
}
15937
15938
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
15939
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
15940
{
15941
    if (node->TabBar == NULL || node->HostWindow == NULL)
15942
        return false;
15943
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
15944
        return false;
15945
    Begin(node->HostWindow->Name);
15946
    PushOverrideID(node->ID);
15947
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node);
15948
    IM_UNUSED(ret);
15949
    IM_ASSERT(ret);
15950
    return true;
15951
}
15952
15953
void ImGui::DockNodeEndAmendTabBar()
15954
{
15955
    EndTabBar();
15956
    PopID();
15957
    End();
15958
}
15959
15960
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
15961
{
15962
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
15963
    ImGuiContext& g = *GImGui;
15964
    if (g.NavWindowingTarget)
15965
        return (g.NavWindowingTarget->DockNode == node);
15966
15967
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
15968
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
15969
    {
15970
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
15971
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
15972
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
15973
            parent_window = parent_window->ParentWindow->RootWindow;
15974
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
15975
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
15976
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
15977
                return true;
15978
    }
15979
    return false;
15980
}
15981
15982
// Submit the tab bar corresponding to a dock node and various housekeeping details.
15983
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
15984
{
15985
    ImGuiContext& g = *GImGui;
15986
    ImGuiStyle& style = g.Style;
15987
15988
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
15989
    const bool closed_all = node->WantCloseAll && node_was_active;
15990
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
15991
    node->WantCloseAll = false;
15992
    node->WantCloseTabId = 0;
15993
15994
    // Decide if we should use a focused title bar color
15995
    bool is_focused = false;
15996
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
15997
    if (IsDockNodeTitleBarHighlighted(node, root_node))
15998
        is_focused = true;
15999
16000
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
16001
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
16002
    {
16003
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16004
        node->IsFocused = is_focused;
16005
        if (is_focused)
16006
            node->LastFrameFocused = g.FrameCount;
16007
        if (node->VisibleWindow)
16008
        {
16009
            // Notify root of visible window (used to display title in OS task bar)
16010
            if (is_focused || root_node->VisibleWindow == NULL)
16011
                root_node->VisibleWindow = node->VisibleWindow;
16012
            if (node->TabBar)
16013
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
16014
        }
16015
        return;
16016
    }
16017
16018
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
16019
    bool backup_skip_item = host_window->SkipItems;
16020
    if (!node->IsDockSpace())
16021
    {
16022
        host_window->SkipItems = false;
16023
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
16024
    }
16025
16026
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
16027
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
16028
    // as docked windows themselves will override the stack with their own root ID.
16029
    PushOverrideID(node->ID);
16030
    ImGuiTabBar* tab_bar = node->TabBar;
16031
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
16032
    if (tab_bar == NULL)
16033
    {
16034
        DockNodeAddTabBar(node);
16035
        tab_bar = node->TabBar;
16036
    }
16037
16038
    ImGuiID focus_tab_id = 0;
16039
    node->IsFocused = is_focused;
16040
16041
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16042
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
16043
16044
    // In a dock node, the Collapse Button turns into the Window Menu button.
16045
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
16046
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
16047
    {
16048
        if (ImGuiID tab_id = DockNodeUpdateWindowMenu(node, tab_bar))
16049
            focus_tab_id = tab_bar->NextSelectedTabId = tab_id;
16050
        is_focused |= node->IsFocused;
16051
    }
16052
16053
    // Layout
16054
    ImRect title_bar_rect, tab_bar_rect;
16055
    ImVec2 window_menu_button_pos;
16056
    ImVec2 close_button_pos;
16057
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
16058
16059
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
16060
    const int tabs_count_old = tab_bar->Tabs.Size;
16061
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16062
    {
16063
        ImGuiWindow* window = node->Windows[window_n];
16064
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
16065
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
16066
    }
16067
16068
    // Title bar
16069
    if (is_focused)
16070
        node->LastFrameFocused = g.FrameCount;
16071
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
16072
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE);
16073
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
16074
16075
    // Docking/Collapse button
16076
    if (has_window_menu_button)
16077
    {
16078
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
16079
            OpenPopup("#WindowMenu");
16080
        if (IsItemActive())
16081
            focus_tab_id = tab_bar->SelectedTabId;
16082
    }
16083
16084
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
16085
    int tabs_unsorted_start = tab_bar->Tabs.Size;
16086
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
16087
    {
16088
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
16089
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
16090
        tabs_unsorted_start = tab_n;
16091
    }
16092
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
16093
    {
16094
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
16095
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
16096
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder);
16097
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
16098
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
16099
    }
16100
16101
    // Apply NavWindow focus back to the tab bar
16102
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
16103
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
16104
16105
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
16106
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
16107
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
16108
    else if (tab_bar->Tabs.Size > tabs_count_old)
16109
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
16110
16111
    // Begin tab bar
16112
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
16113
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
16114
    if (!host_window->Collapsed && is_focused)
16115
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
16116
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node);
16117
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
16118
16119
    // Backup style colors
16120
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
16121
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16122
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
16123
16124
    // Submit actual tabs
16125
    node->VisibleWindow = NULL;
16126
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16127
    {
16128
        ImGuiWindow* window = node->Windows[window_n];
16129
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
16130
            continue;
16131
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
16132
        {
16133
            ImGuiTabItemFlags tab_item_flags = 0;
16134
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
16135
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
16136
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
16137
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
16138
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
16139
16140
            // Apply stored style overrides for the window
16141
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16142
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
16143
16144
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
16145
            bool tab_open = true;
16146
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
16147
            if (!tab_open)
16148
                node->WantCloseTabId = window->TabId;
16149
            if (tab_bar->VisibleTabId == window->TabId)
16150
                node->VisibleWindow = window;
16151
16152
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
16153
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
16154
            window->DockTabItemRect = g.LastItemData.Rect;
16155
16156
            // Update navigation ID on menu layer
16157
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
16158
                host_window->NavLastIds[1] = window->TabId;
16159
        }
16160
    }
16161
16162
    // Restore style colors
16163
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16164
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
16165
16166
    // Notify root of visible window (used to display title in OS task bar)
16167
    if (node->VisibleWindow)
16168
        if (is_focused || root_node->VisibleWindow == NULL)
16169
            root_node->VisibleWindow = node->VisibleWindow;
16170
16171
    // Close button (after VisibleWindow was updated)
16172
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
16173
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
16174
    const bool close_button_is_visible = node->HasCloseButton;
16175
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
16176
    if (close_button_is_visible)
16177
    {
16178
        if (!close_button_is_enabled)
16179
        {
16180
            PushItemFlag(ImGuiItemFlags_Disabled, true);
16181
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
16182
        }
16183
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
16184
        {
16185
            node->WantCloseAll = true;
16186
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
16187
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
16188
        }
16189
        //if (IsItemActive())
16190
        //    focus_tab_id = tab_bar->SelectedTabId;
16191
        if (!close_button_is_enabled)
16192
        {
16193
            PopStyleColor();
16194
            PopItemFlag();
16195
        }
16196
    }
16197
16198
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
16199
    // FIXME: TabItem use AllowItemOverlap so we manually perform a more specific test for now (hovered || held)
16200
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
16201
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
16202
    {
16203
        bool held;
16204
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowItemOverlap);
16205
        if (g.HoveredId == title_bar_id)
16206
        {
16207
            // ImGuiButtonFlags_AllowItemOverlap + SetItemAllowOverlap() required for appending into dock node tab bar,
16208
            // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
16209
            g.LastItemData.ID = title_bar_id;
16210
            SetItemAllowOverlap();
16211
        }
16212
        if (held)
16213
        {
16214
            if (IsMouseClicked(0))
16215
                focus_tab_id = tab_bar->SelectedTabId;
16216
16217
            // Forward moving request to selected window
16218
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
16219
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false);
16220
        }
16221
    }
16222
16223
    // Forward focus from host node to selected window
16224
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
16225
    //    focus_tab_id = tab_bar->SelectedTabId;
16226
16227
    // When clicked on a tab we requested focus to the docked child
16228
    // This overrides the value set by "forward focus from host node to selected window".
16229
    if (tab_bar->NextSelectedTabId)
16230
        focus_tab_id = tab_bar->NextSelectedTabId;
16231
16232
    // Apply navigation focus
16233
    if (focus_tab_id != 0)
16234
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
16235
            if (tab->Window)
16236
            {
16237
                FocusWindow(tab->Window);
16238
                NavInitWindow(tab->Window, false);
16239
            }
16240
16241
    EndTabBar();
16242
    PopID();
16243
16244
    // Restore SkipItems flag
16245
    if (!node->IsDockSpace())
16246
    {
16247
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
16248
        host_window->SkipItems = backup_skip_item;
16249
    }
16250
}
16251
16252
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
16253
{
16254
    IM_ASSERT(node->TabBar == NULL);
16255
    node->TabBar = IM_NEW(ImGuiTabBar);
16256
}
16257
16258
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
16259
{
16260
    if (node->TabBar == NULL)
16261
        return;
16262
    IM_DELETE(node->TabBar);
16263
    node->TabBar = NULL;
16264
}
16265
16266
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
16267
{
16268
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
16269
        return false;
16270
16271
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
16272
    ImGuiWindowClass* payload_class = &payload->WindowClass;
16273
    if (host_class->ClassId != payload_class->ClassId)
16274
    {
16275
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
16276
            return true;
16277
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
16278
            return true;
16279
        return false;
16280
    }
16281
16282
    // Prevent docking any window created above a popup
16283
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
16284
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
16285
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
16286
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
16287
    ImGuiContext& g = *GImGui;
16288
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
16289
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
16290
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
16291
                return false;
16292
16293
    return true;
16294
}
16295
16296
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
16297
{
16298
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
16299
        return true;
16300
16301
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
16302
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
16303
    {
16304
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
16305
        if (DockNodeIsDropAllowedOne(payload, host_window))
16306
            return true;
16307
    }
16308
    return false;
16309
}
16310
16311
// window menu button == collapse button when not in a dock node.
16312
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
16313
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
16314
{
16315
    ImGuiContext& g = *GImGui;
16316
    ImGuiStyle& style = g.Style;
16317
16318
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
16319
    if (out_title_rect) { *out_title_rect = r; }
16320
16321
    r.Min.x += style.WindowBorderSize;
16322
    r.Max.x -= style.WindowBorderSize;
16323
16324
    float button_sz = g.FontSize;
16325
16326
    ImVec2 window_menu_button_pos = r.Min;
16327
    r.Min.x += style.FramePadding.x;
16328
    r.Max.x -= style.FramePadding.x;
16329
    if (node->HasCloseButton)
16330
    {
16331
        r.Max.x -= button_sz;
16332
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - style.FramePadding.x, r.Min.y);
16333
    }
16334
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
16335
    {
16336
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
16337
    }
16338
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
16339
    {
16340
        r.Max.x -= button_sz + style.FramePadding.x;
16341
        window_menu_button_pos = ImVec2(r.Max.x, r.Min.y);
16342
    }
16343
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
16344
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
16345
}
16346
16347
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
16348
{
16349
    ImGuiContext& g = *GImGui;
16350
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
16351
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16352
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
16353
    size_new[axis ^ 1] = size_old[axis ^ 1];
16354
16355
    // Distribute size on given axis (with a desired size or equally)
16356
    const float w_avail = size_old[axis] - dock_spacing;
16357
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
16358
    {
16359
        size_new[axis] = size_new_desired[axis];
16360
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16361
    }
16362
    else
16363
    {
16364
        size_new[axis] = IM_FLOOR(w_avail * 0.5f);
16365
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16366
    }
16367
16368
    // Position each node
16369
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
16370
    {
16371
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
16372
    }
16373
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
16374
    {
16375
        pos_new[axis] = pos_old[axis];
16376
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
16377
    }
16378
}
16379
16380
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
16381
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
16382
{
16383
    ImGuiContext& g = *GImGui;
16384
16385
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
16386
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
16387
    float hs_w; // Half-size, longer axis
16388
    float hs_h; // Half-size, smaller axis
16389
    ImVec2 off; // Distance from edge or center
16390
    if (outer_docking)
16391
    {
16392
        //hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
16393
        //hs_h = ImFloor(hs_w * 0.15f);
16394
        //off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
16395
        hs_w = ImFloor(hs_for_central_nodes * 1.50f);
16396
        hs_h = ImFloor(hs_for_central_nodes * 0.80f);
16397
        off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - hs_h), ImFloor(parent.GetHeight() * 0.5f - hs_h));
16398
    }
16399
    else
16400
    {
16401
        hs_w = ImFloor(hs_for_central_nodes);
16402
        hs_h = ImFloor(hs_for_central_nodes * 0.90f);
16403
        off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f));
16404
    }
16405
16406
    ImVec2 c = ImFloor(parent.GetCenter());
16407
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
16408
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
16409
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
16410
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
16411
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
16412
16413
    if (test_mouse_pos == NULL)
16414
        return false;
16415
16416
    ImRect hit_r = out_r;
16417
    if (!outer_docking)
16418
    {
16419
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
16420
        hit_r.Expand(ImFloor(hs_w * 0.30f));
16421
        ImVec2 mouse_delta = (*test_mouse_pos - c);
16422
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
16423
        float r_threshold_center = hs_w * 1.4f;
16424
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
16425
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
16426
            return (dir == ImGuiDir_None);
16427
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
16428
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
16429
    }
16430
    return hit_r.Contains(*test_mouse_pos);
16431
}
16432
16433
// host_node may be NULL if the window doesn't have a DockNode already.
16434
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
16435
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
16436
{
16437
    ImGuiContext& g = *GImGui;
16438
16439
    // There is an edge case when docking into a dockspace which only has inactive nodes.
16440
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
16441
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
16442
    if (payload_node == NULL)
16443
        payload_node = payload_window->DockNodeAsHost;
16444
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
16445
    if (ref_node_for_rect)
16446
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
16447
16448
    // Filter, figure out where we are allowed to dock
16449
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
16450
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
16451
    data->IsCenterAvailable = true;
16452
    if (is_outer_docking)
16453
        data->IsCenterAvailable = false;
16454
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking)
16455
        data->IsCenterAvailable = false;
16456
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode())
16457
        data->IsCenterAvailable = false;
16458
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
16459
        data->IsCenterAvailable = false;
16460
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
16461
        data->IsCenterAvailable = false;
16462
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
16463
        data->IsCenterAvailable = false;
16464
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
16465
        data->IsCenterAvailable = false;
16466
16467
    data->IsSidesAvailable = true;
16468
    if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit)
16469
        data->IsSidesAvailable = false;
16470
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
16471
        data->IsSidesAvailable = false;
16472
    else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther))
16473
        data->IsSidesAvailable = false;
16474
16475
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
16476
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
16477
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
16478
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
16479
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
16480
16481
    // Calculate drop shapes geometry for allowed splitting directions
16482
    IM_ASSERT(ImGuiDir_None == -1);
16483
    data->SplitNode = host_node;
16484
    data->SplitDir = ImGuiDir_None;
16485
    data->IsSplitDirExplicit = false;
16486
    if (!host_window->Collapsed)
16487
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
16488
        {
16489
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
16490
                continue;
16491
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
16492
                continue;
16493
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
16494
            {
16495
                data->SplitDir = (ImGuiDir)dir;
16496
                data->IsSplitDirExplicit = true;
16497
            }
16498
        }
16499
16500
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
16501
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
16502
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
16503
        data->IsDropAllowed = false;
16504
16505
    // Calculate split area
16506
    data->SplitRatio = 0.0f;
16507
    if (data->SplitDir != ImGuiDir_None)
16508
    {
16509
        ImGuiDir split_dir = data->SplitDir;
16510
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16511
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
16512
        ImVec2 size_new, size_old = data->FutureNode.Size;
16513
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
16514
16515
        // Calculate split ratio so we can pass it down the docking request
16516
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
16517
        data->FutureNode.Pos = pos_new;
16518
        data->FutureNode.Size = size_new;
16519
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
16520
    }
16521
}
16522
16523
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
16524
{
16525
    ImGuiContext& g = *GImGui;
16526
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
16527
16528
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
16529
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
16530
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
16531
16532
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
16533
    int overlay_draw_lists_count = 0;
16534
    ImDrawList* overlay_draw_lists[2];
16535
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
16536
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
16537
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
16538
16539
    // Draw main preview rectangle
16540
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
16541
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
16542
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
16543
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
16544
16545
    // Display area preview
16546
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
16547
    if (data->IsDropAllowed)
16548
    {
16549
        ImRect overlay_rect = data->FutureNode.Rect();
16550
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
16551
            overlay_rect.Min.y += GetFrameHeight();
16552
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
16553
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16554
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE));
16555
    }
16556
16557
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
16558
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
16559
    {
16560
        // Compute target tab bar geometry so we can locate our preview tabs
16561
        ImRect tab_bar_rect;
16562
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
16563
        ImVec2 tab_pos = tab_bar_rect.Min;
16564
        if (host_node && host_node->TabBar)
16565
        {
16566
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
16567
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
16568
            else
16569
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
16570
        }
16571
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
16572
        {
16573
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
16574
        }
16575
16576
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
16577
        if (root_payload->DockNodeAsHost)
16578
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
16579
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
16580
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
16581
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
16582
        {
16583
            // DockNode's TabBar may have non-window Tabs manually appended by user
16584
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
16585
            if (tab_bar_with_payload && payload_window == NULL)
16586
                continue;
16587
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
16588
                continue;
16589
16590
            // Calculate the tab bounding box for each payload window
16591
            ImVec2 tab_size = TabItemCalcSize(payload_window);
16592
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
16593
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
16594
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
16595
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
16596
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
16597
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16598
            {
16599
                ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0);
16600
                if (!tab_bar_rect.Contains(tab_bb))
16601
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
16602
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
16603
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
16604
                if (!tab_bar_rect.Contains(tab_bb))
16605
                    overlay_draw_lists[overlay_n]->PopClipRect();
16606
            }
16607
            PopStyleColor();
16608
        }
16609
    }
16610
16611
    // Display drop boxes
16612
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
16613
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
16614
    {
16615
        if (!data->DropRectsDraw[dir + 1].IsInverted())
16616
        {
16617
            ImRect draw_r = data->DropRectsDraw[dir + 1];
16618
            ImRect draw_r_in = draw_r;
16619
            draw_r_in.Expand(-2.0f);
16620
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
16621
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16622
            {
16623
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
16624
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
16625
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
16626
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
16627
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
16628
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
16629
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
16630
            }
16631
        }
16632
16633
        // Stop after ImGuiDir_None
16634
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
16635
            return;
16636
    }
16637
}
16638
16639
//-----------------------------------------------------------------------------
16640
// Docking: ImGuiDockNode Tree manipulation functions
16641
//-----------------------------------------------------------------------------
16642
// - DockNodeTreeSplit()
16643
// - DockNodeTreeMerge()
16644
// - DockNodeTreeUpdatePosSize()
16645
// - DockNodeTreeUpdateSplitterFindTouchingNode()
16646
// - DockNodeTreeUpdateSplitter()
16647
// - DockNodeTreeFindFallbackLeafNode()
16648
// - DockNodeTreeFindNodeByPos()
16649
//-----------------------------------------------------------------------------
16650
16651
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
16652
{
16653
    ImGuiContext& g = *GImGui;
16654
    IM_ASSERT(split_axis != ImGuiAxis_None);
16655
16656
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
16657
    child_0->ParentNode = parent_node;
16658
16659
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
16660
    child_1->ParentNode = parent_node;
16661
16662
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
16663
    DockNodeMoveChildNodes(child_inheritor, parent_node);
16664
    parent_node->ChildNodes[0] = child_0;
16665
    parent_node->ChildNodes[1] = child_1;
16666
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
16667
    parent_node->SplitAxis = split_axis;
16668
    parent_node->VisibleWindow = NULL;
16669
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16670
16671
    float size_avail = (parent_node->Size[split_axis] - DOCKING_SPLITTER_SIZE);
16672
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
16673
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
16674
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
16675
    child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio);
16676
    child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]);
16677
16678
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
16679
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
16680
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
16681
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
16682
16683
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
16684
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16685
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16686
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16687
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16688
    child_0->UpdateMergedFlags();
16689
    child_1->UpdateMergedFlags();
16690
    parent_node->UpdateMergedFlags();
16691
    if (child_inheritor->IsCentralNode())
16692
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
16693
}
16694
16695
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
16696
{
16697
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
16698
    ImGuiContext& g = *GImGui;
16699
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
16700
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
16701
    IM_ASSERT(child_0 || child_1);
16702
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
16703
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
16704
    {
16705
        IM_ASSERT(parent_node->TabBar == NULL);
16706
        IM_ASSERT(parent_node->Windows.Size == 0);
16707
    }
16708
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
16709
16710
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
16711
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
16712
    if (child_0)
16713
    {
16714
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
16715
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
16716
    }
16717
    if (child_1)
16718
    {
16719
        DockNodeMoveWindows(parent_node, child_1);
16720
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
16721
    }
16722
    DockNodeApplyPosSizeToWindows(parent_node);
16723
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16724
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
16725
    parent_node->SizeRef = backup_last_explicit_size;
16726
16727
    // Flags transfer
16728
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
16729
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16730
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16731
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
16732
    parent_node->UpdateMergedFlags();
16733
16734
    if (child_0)
16735
    {
16736
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
16737
        IM_DELETE(child_0);
16738
    }
16739
    if (child_1)
16740
    {
16741
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
16742
        IM_DELETE(child_1);
16743
    }
16744
}
16745
16746
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
16747
// (Depth-first, Pre-Order)
16748
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
16749
{
16750
    // During the regular dock node update we write to all nodes.
16751
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
16752
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
16753
    if (write_to_node)
16754
    {
16755
        node->Pos = pos;
16756
        node->Size = size;
16757
    }
16758
16759
    if (node->IsLeafNode())
16760
        return;
16761
16762
    ImGuiDockNode* child_0 = node->ChildNodes[0];
16763
    ImGuiDockNode* child_1 = node->ChildNodes[1];
16764
    ImVec2 child_0_pos = pos, child_1_pos = pos;
16765
    ImVec2 child_0_size = size, child_1_size = size;
16766
16767
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
16768
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
16769
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
16770
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
16771
16772
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
16773
    {
16774
        ImGuiContext& g = *GImGui;
16775
        const float spacing = DOCKING_SPLITTER_SIZE;
16776
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
16777
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
16778
16779
        // Size allocation policy
16780
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
16781
        const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
16782
16783
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
16784
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImFloor()
16785
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
16786
16787
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
16788
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
16789
        {
16790
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
16791
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
16792
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
16793
        }
16794
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
16795
        {
16796
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
16797
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
16798
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
16799
        }
16800
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
16801
        {
16802
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
16803
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
16804
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
16805
            child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * split_ratio);
16806
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
16807
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
16808
        }
16809
16810
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
16811
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
16812
        {
16813
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
16814
            child_1_size[axis] = (size_avail - child_0_size[axis]);
16815
        }
16816
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
16817
        {
16818
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
16819
            child_0_size[axis] = (size_avail - child_1_size[axis]);
16820
        }
16821
        else
16822
        {
16823
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
16824
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
16825
            child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5f));
16826
            child_1_size[axis] = (size_avail - child_0_size[axis]);
16827
        }
16828
16829
        child_1_pos[axis] += spacing + child_0_size[axis];
16830
    }
16831
16832
    if (only_write_to_single_node == NULL)
16833
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
16834
16835
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
16836
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
16837
    if (child_0_recurse)
16838
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
16839
    if (child_1_recurse)
16840
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
16841
}
16842
16843
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
16844
{
16845
    if (node->IsLeafNode())
16846
    {
16847
        touching_nodes->push_back(node);
16848
        return;
16849
    }
16850
    if (node->ChildNodes[0]->IsVisible)
16851
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
16852
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
16853
    if (node->ChildNodes[1]->IsVisible)
16854
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
16855
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
16856
}
16857
16858
// (Depth-First, Pre-Order)
16859
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
16860
{
16861
    if (node->IsLeafNode())
16862
        return;
16863
16864
    ImGuiContext& g = *GImGui;
16865
16866
    ImGuiDockNode* child_0 = node->ChildNodes[0];
16867
    ImGuiDockNode* child_1 = node->ChildNodes[1];
16868
    if (child_0->IsVisible && child_1->IsVisible)
16869
    {
16870
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
16871
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
16872
        IM_ASSERT(axis != ImGuiAxis_None);
16873
        ImRect bb;
16874
        bb.Min = child_0->Pos;
16875
        bb.Max = child_1->Pos;
16876
        bb.Min[axis] += child_0->Size[axis];
16877
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
16878
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
16879
16880
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
16881
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
16882
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
16883
        {
16884
            ImGuiWindow* window = g.CurrentWindow;
16885
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
16886
        }
16887
        else
16888
        {
16889
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
16890
            //bb.Max[axis] -= 1;
16891
            PushID(node->ID);
16892
16893
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
16894
            ImVector<ImGuiDockNode*> touching_nodes[2];
16895
            float min_size = g.Style.WindowMinSize[axis];
16896
            float resize_limits[2];
16897
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
16898
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
16899
16900
            ImGuiID splitter_id = GetID("##Splitter");
16901
            if (g.ActiveId == splitter_id) // Only process when splitter is active
16902
            {
16903
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
16904
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
16905
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
16906
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
16907
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
16908
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
16909
16910
                // [DEBUG] Render touching nodes & limits
16911
                /*
16912
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
16913
                for (int n = 0; n < 2; n++)
16914
                {
16915
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
16916
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
16917
                    if (axis == ImGuiAxis_X)
16918
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
16919
                    else
16920
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
16921
                }
16922
                */
16923
            }
16924
16925
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
16926
            float cur_size_0 = child_0->Size[axis];
16927
            float cur_size_1 = child_1->Size[axis];
16928
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
16929
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
16930
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
16931
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
16932
            {
16933
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
16934
                {
16935
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
16936
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
16937
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
16938
16939
                    // Lock the size of every node that is a sibling of the node we are touching
16940
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
16941
                    for (int side_n = 0; side_n < 2; side_n++)
16942
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
16943
                        {
16944
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
16945
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
16946
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
16947
                            while (touching_node->ParentNode != node)
16948
                            {
16949
                                if (touching_node->ParentNode->SplitAxis == axis)
16950
                                {
16951
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
16952
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
16953
                                    node_to_preserve->WantLockSizeOnce = true;
16954
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
16955
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
16956
                                }
16957
                                touching_node = touching_node->ParentNode;
16958
                            }
16959
                        }
16960
16961
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
16962
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
16963
                    MarkIniSettingsDirty();
16964
                }
16965
            }
16966
            PopID();
16967
        }
16968
    }
16969
16970
    if (child_0->IsVisible)
16971
        DockNodeTreeUpdateSplitter(child_0);
16972
    if (child_1->IsVisible)
16973
        DockNodeTreeUpdateSplitter(child_1);
16974
}
16975
16976
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
16977
{
16978
    if (node->IsLeafNode())
16979
        return node;
16980
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
16981
        return leaf_node;
16982
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
16983
        return leaf_node;
16984
    return NULL;
16985
}
16986
16987
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
16988
{
16989
    if (!node->IsVisible)
16990
        return NULL;
16991
16992
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
16993
    ImRect r(node->Pos, node->Pos + node->Size);
16994
    r.Expand(dock_spacing * 0.5f);
16995
    bool inside = r.Contains(pos);
16996
    if (!inside)
16997
        return NULL;
16998
16999
    if (node->IsLeafNode())
17000
        return node;
17001
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
17002
        return hovered_node;
17003
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
17004
        return hovered_node;
17005
17006
    // This means we are hovering over the splitter/spacing of a parent node
17007
    return node;
17008
}
17009
17010
//-----------------------------------------------------------------------------
17011
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17012
//-----------------------------------------------------------------------------
17013
// - SetWindowDock() [Internal]
17014
// - DockSpace()
17015
// - DockSpaceOverViewport()
17016
//-----------------------------------------------------------------------------
17017
17018
// [Internal] Called via SetNextWindowDockID()
17019
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
17020
{
17021
    // Test condition (NB: bit 0 is always true) and clear flags for next time
17022
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
17023
        return;
17024
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
17025
17026
    if (window->DockId == dock_id)
17027
        return;
17028
17029
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
17030
    ImGuiContext* ctx = GImGui;
17031
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
17032
        if (new_node->IsSplitNode())
17033
        {
17034
            // Policy: Find central node or latest focused node. We first move back to our root node.
17035
            new_node = DockNodeGetRootNode(new_node);
17036
            if (new_node->CentralNode)
17037
            {
17038
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
17039
                dock_id = new_node->CentralNode->ID;
17040
            }
17041
            else
17042
            {
17043
                dock_id = new_node->LastFocusedNodeId;
17044
            }
17045
        }
17046
17047
    if (window->DockId == dock_id)
17048
        return;
17049
17050
    if (window->DockNode)
17051
        DockNodeRemoveWindow(window->DockNode, window, 0);
17052
    window->DockId = dock_id;
17053
}
17054
17055
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
17056
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
17057
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
17058
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
17059
{
17060
    ImGuiContext* ctx = GImGui;
17061
    ImGuiContext& g = *ctx;
17062
    ImGuiWindow* window = GetCurrentWindow();
17063
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17064
        return 0;
17065
17066
    // Early out if parent window is hidden/collapsed
17067
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
17068
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
17069
    if (window->SkipItems)
17070
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
17071
17072
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
17073
    IM_ASSERT(id != 0);
17074
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
17075
    if (!node)
17076
    {
17077
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
17078
        node = DockContextAddNode(ctx, id);
17079
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
17080
    }
17081
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
17082
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
17083
    node->SharedFlags = flags;
17084
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
17085
17086
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
17087
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
17088
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
17089
    {
17090
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
17091
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17092
        return id;
17093
    }
17094
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17095
17096
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
17097
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
17098
    {
17099
        node->LastFrameAlive = g.FrameCount;
17100
        return id;
17101
    }
17102
17103
    const ImVec2 content_avail = GetContentRegionAvail();
17104
    ImVec2 size = ImFloor(size_arg);
17105
    if (size.x <= 0.0f)
17106
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
17107
    if (size.y <= 0.0f)
17108
        size.y = ImMax(content_avail.y + size.y, 4.0f);
17109
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17110
17111
    node->Pos = window->DC.CursorPos;
17112
    node->Size = node->SizeRef = size;
17113
    SetNextWindowPos(node->Pos);
17114
    SetNextWindowSize(node->Size);
17115
    g.NextWindowData.PosUndock = false;
17116
17117
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
17118
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
17119
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
17120
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
17121
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
17122
    window_flags |= ImGuiWindowFlags_NoBackground;
17123
17124
    char title[256];
17125
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
17126
17127
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
17128
    Begin(title, NULL, window_flags);
17129
    PopStyleVar();
17130
17131
    ImGuiWindow* host_window = g.CurrentWindow;
17132
    DockNodeSetupHostWindow(node, host_window);
17133
    host_window->ChildId = window->GetID(title);
17134
    node->OnlyNodeWithWindows = NULL;
17135
17136
    IM_ASSERT(node->IsRootNode());
17137
17138
    // We need to handle the rare case were a central node is missing.
17139
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
17140
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
17141
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
17142
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
17143
    // as it doesn't make sense for an empty dockspace to not have this property.
17144
    if (node->IsLeafNode() && !node->IsCentralNode())
17145
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17146
17147
    // Update the node
17148
    DockNodeUpdate(node);
17149
17150
    End();
17151
    ItemSize(size);
17152
    return id;
17153
}
17154
17155
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
17156
// The limitation with this call is that your window won't have a menu bar.
17157
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
17158
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
17159
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
17160
{
17161
    if (viewport == NULL)
17162
        viewport = GetMainViewport();
17163
17164
    SetNextWindowPos(viewport->WorkPos);
17165
    SetNextWindowSize(viewport->WorkSize);
17166
    SetNextWindowViewport(viewport->ID);
17167
17168
    ImGuiWindowFlags host_window_flags = 0;
17169
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
17170
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
17171
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
17172
        host_window_flags |= ImGuiWindowFlags_NoBackground;
17173
17174
    char label[32];
17175
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
17176
17177
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
17178
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
17179
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
17180
    Begin(label, NULL, host_window_flags);
17181
    PopStyleVar(3);
17182
17183
    ImGuiID dockspace_id = GetID("DockSpace");
17184
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
17185
    End();
17186
17187
    return dockspace_id;
17188
}
17189
17190
//-----------------------------------------------------------------------------
17191
// Docking: Builder Functions
17192
//-----------------------------------------------------------------------------
17193
// Very early end-user API to manipulate dock nodes.
17194
// Only available in imgui_internal.h. Expect this API to change/break!
17195
// It is expected that those functions are all called _before_ the dockspace node submission.
17196
//-----------------------------------------------------------------------------
17197
// - DockBuilderDockWindow()
17198
// - DockBuilderGetNode()
17199
// - DockBuilderSetNodePos()
17200
// - DockBuilderSetNodeSize()
17201
// - DockBuilderAddNode()
17202
// - DockBuilderRemoveNode()
17203
// - DockBuilderRemoveNodeChildNodes()
17204
// - DockBuilderRemoveNodeDockedWindows()
17205
// - DockBuilderSplitNode()
17206
// - DockBuilderCopyNodeRec()
17207
// - DockBuilderCopyNode()
17208
// - DockBuilderCopyWindowSettings()
17209
// - DockBuilderCopyDockSpace()
17210
// - DockBuilderFinish()
17211
//-----------------------------------------------------------------------------
17212
17213
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
17214
{
17215
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
17216
    ImGuiID window_id = ImHashStr(window_name);
17217
    if (ImGuiWindow* window = FindWindowByID(window_id))
17218
    {
17219
        // Apply to created window
17220
        SetWindowDock(window, node_id, ImGuiCond_Always);
17221
        window->DockOrder = -1;
17222
    }
17223
    else
17224
    {
17225
        // Apply to settings
17226
        ImGuiWindowSettings* settings = FindWindowSettings(window_id);
17227
        if (settings == NULL)
17228
            settings = CreateNewWindowSettings(window_name);
17229
        settings->DockId = node_id;
17230
        settings->DockOrder = -1;
17231
    }
17232
}
17233
17234
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
17235
{
17236
    ImGuiContext* ctx = GImGui;
17237
    return DockContextFindNodeByID(ctx, node_id);
17238
}
17239
17240
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
17241
{
17242
    ImGuiContext* ctx = GImGui;
17243
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17244
    if (node == NULL)
17245
        return;
17246
    node->Pos = pos;
17247
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
17248
}
17249
17250
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
17251
{
17252
    ImGuiContext* ctx = GImGui;
17253
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17254
    if (node == NULL)
17255
        return;
17256
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17257
    node->Size = node->SizeRef = size;
17258
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17259
}
17260
17261
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
17262
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
17263
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
17264
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
17265
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
17266
// - Use (id == 0) to let the system allocate a node identifier.
17267
// - Existing node with a same id will be removed.
17268
ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags)
17269
{
17270
    ImGuiContext* ctx = GImGui;
17271
17272
    if (id != 0)
17273
        DockBuilderRemoveNode(id);
17274
17275
    ImGuiDockNode* node = NULL;
17276
    if (flags & ImGuiDockNodeFlags_DockSpace)
17277
    {
17278
        DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
17279
        node = DockContextFindNodeByID(ctx, id);
17280
    }
17281
    else
17282
    {
17283
        node = DockContextAddNode(ctx, id);
17284
        node->SetLocalFlags(flags);
17285
    }
17286
    node->LastFrameAlive = ctx->FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
17287
    return node->ID;
17288
}
17289
17290
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
17291
{
17292
    ImGuiContext* ctx = GImGui;
17293
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17294
    if (node == NULL)
17295
        return;
17296
    DockBuilderRemoveNodeDockedWindows(node_id, true);
17297
    DockBuilderRemoveNodeChildNodes(node_id);
17298
    // Node may have moved or deleted if e.g. any merge happened
17299
    node = DockContextFindNodeByID(ctx, node_id);
17300
    if (node == NULL)
17301
        return;
17302
    if (node->IsCentralNode() && node->ParentNode)
17303
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17304
    DockContextRemoveNode(ctx, node, true);
17305
}
17306
17307
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
17308
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
17309
{
17310
    ImGuiContext* ctx = GImGui;
17311
    ImGuiDockContext* dc  = &ctx->DockContext;
17312
17313
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
17314
    if (root_id && root_node == NULL)
17315
        return;
17316
    bool has_central_node = false;
17317
17318
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
17319
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
17320
17321
    // Process active windows
17322
    ImVector<ImGuiDockNode*> nodes_to_remove;
17323
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
17324
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17325
        {
17326
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
17327
            if (want_removal)
17328
            {
17329
                if (node->IsCentralNode())
17330
                    has_central_node = true;
17331
                if (root_id != 0)
17332
                    DockContextQueueNotifyRemovedNode(ctx, node);
17333
                if (root_node)
17334
                {
17335
                    DockNodeMoveWindows(root_node, node);
17336
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
17337
                }
17338
                nodes_to_remove.push_back(node);
17339
            }
17340
        }
17341
17342
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
17343
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
17344
    if (root_node)
17345
    {
17346
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
17347
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
17348
    }
17349
17350
    // Apply to settings
17351
    for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
17352
        if (ImGuiID window_settings_dock_id = settings->DockId)
17353
            for (int n = 0; n < nodes_to_remove.Size; n++)
17354
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
17355
                {
17356
                    settings->DockId = root_id;
17357
                    break;
17358
                }
17359
17360
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
17361
    if (nodes_to_remove.Size > 1)
17362
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
17363
    for (int n = 0; n < nodes_to_remove.Size; n++)
17364
        DockContextRemoveNode(ctx, nodes_to_remove[n], false);
17365
17366
    if (root_id == 0)
17367
    {
17368
        dc->Nodes.Clear();
17369
        dc->Requests.clear();
17370
    }
17371
    else if (has_central_node)
17372
    {
17373
        root_node->CentralNode = root_node;
17374
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17375
    }
17376
}
17377
17378
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
17379
{
17380
    // Clear references in settings
17381
    ImGuiContext* ctx = GImGui;
17382
    ImGuiContext& g = *ctx;
17383
    if (clear_settings_refs)
17384
    {
17385
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
17386
        {
17387
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
17388
            if (!want_removal && settings->DockId != 0)
17389
                if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
17390
                    if (DockNodeGetRootNode(node)->ID == root_id)
17391
                        want_removal = true;
17392
            if (want_removal)
17393
                settings->DockId = 0;
17394
        }
17395
    }
17396
17397
    // Clear references in windows
17398
    for (int n = 0; n < g.Windows.Size; n++)
17399
    {
17400
        ImGuiWindow* window = g.Windows[n];
17401
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
17402
        if (want_removal)
17403
        {
17404
            const ImGuiID backup_dock_id = window->DockId;
17405
            IM_UNUSED(backup_dock_id);
17406
            DockContextProcessUndockWindow(ctx, window, clear_settings_refs);
17407
            if (!clear_settings_refs)
17408
                IM_ASSERT(window->DockId == backup_dock_id);
17409
        }
17410
    }
17411
}
17412
17413
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
17414
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
17415
// FIXME-DOCK: We are not exposing nor using split_outer.
17416
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
17417
{
17418
    ImGuiContext& g = *GImGui;
17419
    IM_ASSERT(split_dir != ImGuiDir_None);
17420
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
17421
17422
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
17423
    if (node == NULL)
17424
    {
17425
        IM_ASSERT(node != NULL);
17426
        return 0;
17427
    }
17428
17429
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
17430
17431
    ImGuiDockRequest req;
17432
    req.Type = ImGuiDockRequestType_Split;
17433
    req.DockTargetWindow = NULL;
17434
    req.DockTargetNode = node;
17435
    req.DockPayload = NULL;
17436
    req.DockSplitDir = split_dir;
17437
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
17438
    req.DockSplitOuter = false;
17439
    DockContextProcessDock(&g, &req);
17440
17441
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
17442
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
17443
    if (out_id_at_dir)
17444
        *out_id_at_dir = id_at_dir;
17445
    if (out_id_at_opposite_dir)
17446
        *out_id_at_opposite_dir = id_at_opposite_dir;
17447
    return id_at_dir;
17448
}
17449
17450
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
17451
{
17452
    ImGuiContext& g = *GImGui;
17453
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
17454
    dst_node->SharedFlags = src_node->SharedFlags;
17455
    dst_node->LocalFlags = src_node->LocalFlags;
17456
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
17457
    dst_node->Pos = src_node->Pos;
17458
    dst_node->Size = src_node->Size;
17459
    dst_node->SizeRef = src_node->SizeRef;
17460
    dst_node->SplitAxis = src_node->SplitAxis;
17461
    dst_node->UpdateMergedFlags();
17462
17463
    out_node_remap_pairs->push_back(src_node->ID);
17464
    out_node_remap_pairs->push_back(dst_node->ID);
17465
17466
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
17467
        if (src_node->ChildNodes[child_n])
17468
        {
17469
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
17470
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
17471
        }
17472
17473
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
17474
    return dst_node;
17475
}
17476
17477
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
17478
{
17479
    ImGuiContext* ctx = GImGui;
17480
    IM_ASSERT(src_node_id != 0);
17481
    IM_ASSERT(dst_node_id != 0);
17482
    IM_ASSERT(out_node_remap_pairs != NULL);
17483
17484
    DockBuilderRemoveNode(dst_node_id);
17485
17486
    ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
17487
    IM_ASSERT(src_node != NULL);
17488
17489
    out_node_remap_pairs->clear();
17490
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
17491
17492
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
17493
}
17494
17495
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
17496
{
17497
    ImGuiWindow* src_window = FindWindowByName(src_name);
17498
    if (src_window == NULL)
17499
        return;
17500
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
17501
    {
17502
        dst_window->Pos = src_window->Pos;
17503
        dst_window->Size = src_window->Size;
17504
        dst_window->SizeFull = src_window->SizeFull;
17505
        dst_window->Collapsed = src_window->Collapsed;
17506
    }
17507
    else if (ImGuiWindowSettings* dst_settings = FindOrCreateWindowSettings(dst_name))
17508
    {
17509
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
17510
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
17511
        {
17512
            dst_settings->ViewportPos = window_pos_2ih;
17513
            dst_settings->ViewportId = src_window->ViewportId;
17514
            dst_settings->Pos = ImVec2ih(0, 0);
17515
        }
17516
        else
17517
        {
17518
            dst_settings->Pos = window_pos_2ih;
17519
        }
17520
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
17521
        dst_settings->Collapsed = src_window->Collapsed;
17522
    }
17523
}
17524
17525
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
17526
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
17527
{
17528
    ImGuiContext& g = *GImGui;
17529
    IM_ASSERT(src_dockspace_id != 0);
17530
    IM_ASSERT(dst_dockspace_id != 0);
17531
    IM_ASSERT(in_window_remap_pairs != NULL);
17532
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
17533
17534
    // Duplicate entire dock
17535
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
17536
    // whereas we could attempt to at least keep them together in a new, same floating node.
17537
    ImVector<ImGuiID> node_remap_pairs;
17538
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
17539
17540
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
17541
    // (The windows associated to src_dockspace_id are staying in place)
17542
    ImVector<ImGuiID> src_windows;
17543
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
17544
    {
17545
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
17546
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
17547
        ImGuiID src_window_id = ImHashStr(src_window_name);
17548
        src_windows.push_back(src_window_id);
17549
17550
        // Search in the remapping tables
17551
        ImGuiID src_dock_id = 0;
17552
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
17553
            src_dock_id = src_window->DockId;
17554
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettings(src_window_id))
17555
            src_dock_id = src_window_settings->DockId;
17556
        ImGuiID dst_dock_id = 0;
17557
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
17558
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
17559
            {
17560
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
17561
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
17562
                break;
17563
            }
17564
17565
        if (dst_dock_id != 0)
17566
        {
17567
            // Docked windows gets redocked into the new node hierarchy.
17568
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
17569
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
17570
        }
17571
        else
17572
        {
17573
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
17574
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
17575
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
17576
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
17577
        }
17578
    }
17579
17580
    // Anything else in the source nodes of 'node_remap_pairs' are windows that were docked in src_dockspace_id but are not owned by it (unaffiliated windows, e.g. "ImGui Demo")
17581
    // Find those windows and move to them to the cloned dock node. This may be optional?
17582
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
17583
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
17584
        {
17585
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
17586
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
17587
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17588
            {
17589
                ImGuiWindow* window = node->Windows[window_n];
17590
                if (src_windows.contains(window->ID))
17591
                    continue;
17592
17593
                // Docked windows gets redocked into the new node hierarchy.
17594
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
17595
                DockBuilderDockWindow(window->Name, dst_dock_id);
17596
            }
17597
        }
17598
}
17599
17600
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
17601
void ImGui::DockBuilderFinish(ImGuiID root_id)
17602
{
17603
    ImGuiContext* ctx = GImGui;
17604
    //DockContextRebuild(ctx);
17605
    DockContextBuildAddWindowsToNodes(ctx, root_id);
17606
}
17607
17608
//-----------------------------------------------------------------------------
17609
// Docking: Begin/End Support Functions (called from Begin/End)
17610
//-----------------------------------------------------------------------------
17611
// - GetWindowAlwaysWantOwnTabBar()
17612
// - DockContextBindNodeToWindow()
17613
// - BeginDocked()
17614
// - BeginDockableDragDropSource()
17615
// - BeginDockableDragDropTarget()
17616
//-----------------------------------------------------------------------------
17617
17618
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
17619
{
17620
    ImGuiContext& g = *GImGui;
17621
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
17622
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
17623
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
17624
                return true;
17625
    return false;
17626
}
17627
17628
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
17629
{
17630
    ImGuiContext& g = *ctx;
17631
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
17632
    IM_ASSERT(window->DockNode == NULL);
17633
17634
    // We should not be docking into a split node (SetWindowDock should avoid this)
17635
    if (node && node->IsSplitNode())
17636
    {
17637
        DockContextProcessUndockWindow(ctx, window);
17638
        return NULL;
17639
    }
17640
17641
    // Create node
17642
    if (node == NULL)
17643
    {
17644
        node = DockContextAddNode(ctx, window->DockId);
17645
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
17646
        node->LastFrameAlive = g.FrameCount;
17647
    }
17648
17649
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
17650
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
17651
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
17652
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
17653
    if (!node->IsVisible)
17654
    {
17655
        ImGuiDockNode* ancestor_node = node;
17656
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
17657
            ancestor_node = ancestor_node->ParentNode;
17658
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
17659
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
17660
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
17661
    }
17662
17663
    // Add window to node
17664
    bool node_was_visible = node->IsVisible;
17665
    DockNodeAddWindow(node, window, true);
17666
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
17667
    IM_ASSERT(node == window->DockNode);
17668
    return node;
17669
}
17670
17671
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
17672
{
17673
    ImGuiContext* ctx = GImGui;
17674
    ImGuiContext& g = *ctx;
17675
17676
    // Clear fields ahead so most early-out paths don't have to do it
17677
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
17678
17679
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
17680
    if (auto_dock_node)
17681
    {
17682
        if (window->DockId == 0)
17683
        {
17684
            IM_ASSERT(window->DockNode == NULL);
17685
            window->DockId = DockContextGenNodeID(ctx);
17686
        }
17687
    }
17688
    else
17689
    {
17690
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
17691
        bool want_undock = false;
17692
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
17693
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
17694
        if (want_undock)
17695
        {
17696
            DockContextProcessUndockWindow(ctx, window);
17697
            return;
17698
        }
17699
    }
17700
17701
    // Bind to our dock node
17702
    ImGuiDockNode* node = window->DockNode;
17703
    if (node != NULL)
17704
        IM_ASSERT(window->DockId == node->ID);
17705
    if (window->DockId != 0 && node == NULL)
17706
    {
17707
        node = DockContextBindNodeToWindow(ctx, window);
17708
        if (node == NULL)
17709
            return;
17710
    }
17711
17712
#if 0
17713
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
17714
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
17715
    {
17716
        DockContextProcessUndockWindow(ctx, window);
17717
        return;
17718
    }
17719
#endif
17720
17721
    // Undock if our dockspace node disappeared
17722
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
17723
    if (node->LastFrameAlive < g.FrameCount)
17724
    {
17725
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
17726
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17727
        if (root_node->LastFrameAlive < g.FrameCount)
17728
            DockContextProcessUndockWindow(ctx, window);
17729
        else
17730
            window->DockIsActive = true;
17731
        return;
17732
    }
17733
17734
    // Store style overrides
17735
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17736
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
17737
17738
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
17739
    // and never create neither a host window neither a tab bar.
17740
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
17741
    if (node->HostWindow == NULL)
17742
    {
17743
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
17744
            window->DockIsActive = true;
17745
        if (node->Windows.Size > 1)
17746
            DockNodeHideWindowDuringHostWindowCreation(window);
17747
        return;
17748
    }
17749
17750
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
17751
    IM_ASSERT(node->HostWindow);
17752
    IM_ASSERT(node->IsLeafNode());
17753
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
17754
    node->State = ImGuiDockNodeState_HostWindowVisible;
17755
17756
    // Undock if we are submitted earlier than the host window
17757
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
17758
    {
17759
        DockContextProcessUndockWindow(ctx, window);
17760
        return;
17761
    }
17762
17763
    // Position/Size window
17764
    SetNextWindowPos(node->Pos);
17765
    SetNextWindowSize(node->Size);
17766
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
17767
    window->DockIsActive = true;
17768
    window->DockNodeIsVisible = true;
17769
    window->DockTabIsVisible = false;
17770
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
17771
        return;
17772
17773
    // When the window is selected we mark it as visible.
17774
    if (node->VisibleWindow == window)
17775
        window->DockTabIsVisible = true;
17776
17777
    // Update window flag
17778
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
17779
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
17780
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
17781
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
17782
    else
17783
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
17784
17785
    // Save new dock order only if the window has been visible once already
17786
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
17787
    if (node->TabBar && window->WasActive)
17788
        window->DockOrder = (short)DockNodeGetTabOrder(window);
17789
17790
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
17791
        *p_open = false;
17792
17793
    // Update ChildId to allow returning from Child to Parent with Escape
17794
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
17795
    window->ChildId = parent_window->GetID(window->Name);
17796
}
17797
17798
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
17799
{
17800
    ImGuiContext& g = *GImGui;
17801
    IM_ASSERT(g.ActiveId == window->MoveId);
17802
    IM_ASSERT(g.MovingWindow == window);
17803
    IM_ASSERT(g.CurrentWindow == window);
17804
17805
    g.LastItemData.ID = window->MoveId;
17806
    window = window->RootWindowDockTree;
17807
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
17808
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
17809
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
17810
    {
17811
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
17812
        EndDragDropSource();
17813
17814
        // Store style overrides
17815
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17816
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
17817
    }
17818
}
17819
17820
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
17821
{
17822
    ImGuiContext* ctx = GImGui;
17823
    ImGuiContext& g = *ctx;
17824
17825
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
17826
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
17827
    if (!g.DragDropActive)
17828
        return;
17829
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
17830
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
17831
        return;
17832
17833
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
17834
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
17835
    const ImGuiPayload* payload = &g.DragDropPayload;
17836
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
17837
    {
17838
        EndDragDropTarget();
17839
        return;
17840
    }
17841
17842
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
17843
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
17844
    {
17845
        // Select target node
17846
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
17847
        bool dock_into_floating_window = false;
17848
        ImGuiDockNode* node = NULL;
17849
        if (window->DockNodeAsHost)
17850
        {
17851
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
17852
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
17853
17854
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
17855
            // In this case we need to fallback into any leaf mode, possibly the central node.
17856
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
17857
            if (node && node->IsDockSpace() && node->IsRootNode())
17858
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
17859
        }
17860
        else
17861
        {
17862
            if (window->DockNode)
17863
                node = window->DockNode;
17864
            else
17865
                dock_into_floating_window = true; // Dock into a regular window
17866
        }
17867
17868
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
17869
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
17870
17871
        // Preview docking request and find out split direction/ratio
17872
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
17873
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
17874
        if (do_preview && (node != NULL || dock_into_floating_window))
17875
        {
17876
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
17877
            ImGuiDockPreviewData split_inner;
17878
            ImGuiDockPreviewData split_outer;
17879
            ImGuiDockPreviewData* split_data = &split_inner;
17880
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
17881
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
17882
                {
17883
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
17884
                    if (split_outer.IsSplitDirExplicit)
17885
                        split_data = &split_outer;
17886
                }
17887
            if (!node || node->IsLeafNode())
17888
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
17889
            if (split_data == &split_outer)
17890
                split_inner.IsDropAllowed = false;
17891
17892
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
17893
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
17894
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
17895
17896
            // Queue docking request
17897
            if (split_data->IsDropAllowed && payload->IsDelivery())
17898
                DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
17899
        }
17900
    }
17901
    EndDragDropTarget();
17902
}
17903
17904
//-----------------------------------------------------------------------------
17905
// Docking: Settings
17906
//-----------------------------------------------------------------------------
17907
// - DockSettingsRenameNodeReferences()
17908
// - DockSettingsRemoveNodeReferences()
17909
// - DockSettingsFindNodeSettings()
17910
// - DockSettingsHandler_ApplyAll()
17911
// - DockSettingsHandler_ReadOpen()
17912
// - DockSettingsHandler_ReadLine()
17913
// - DockSettingsHandler_DockNodeToSettings()
17914
// - DockSettingsHandler_WriteAll()
17915
//-----------------------------------------------------------------------------
17916
17917
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
17918
{
17919
    ImGuiContext& g = *GImGui;
17920
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
17921
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
17922
    {
17923
        ImGuiWindow* window = g.Windows[window_n];
17924
        if (window->DockId == old_node_id && window->DockNode == NULL)
17925
            window->DockId = new_node_id;
17926
    }
17927
    //// FIXME-OPT: We could remove this loop by storing the index in the map
17928
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
17929
        if (settings->DockId == old_node_id)
17930
            settings->DockId = new_node_id;
17931
}
17932
17933
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
17934
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
17935
{
17936
    ImGuiContext& g = *GImGui;
17937
    int found = 0;
17938
    //// FIXME-OPT: We could remove this loop by storing the index in the map
17939
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
17940
        for (int node_n = 0; node_n < node_ids_count; node_n++)
17941
            if (settings->DockId == node_ids[node_n])
17942
            {
17943
                settings->DockId = 0;
17944
                settings->DockOrder = -1;
17945
                if (++found < node_ids_count)
17946
                    break;
17947
                return;
17948
            }
17949
}
17950
17951
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
17952
{
17953
    // FIXME-OPT
17954
    ImGuiDockContext* dc  = &ctx->DockContext;
17955
    for (int n = 0; n < dc->NodesSettings.Size; n++)
17956
        if (dc->NodesSettings[n].ID == id)
17957
            return &dc->NodesSettings[n];
17958
    return NULL;
17959
}
17960
17961
// Clear settings data
17962
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
17963
{
17964
    ImGuiDockContext* dc  = &ctx->DockContext;
17965
    dc->NodesSettings.clear();
17966
    DockContextClearNodes(ctx, 0, true);
17967
}
17968
17969
// Recreate nodes based on settings data
17970
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
17971
{
17972
    // Prune settings at boot time only
17973
    ImGuiDockContext* dc  = &ctx->DockContext;
17974
    if (ctx->Windows.Size == 0)
17975
        DockContextPruneUnusedSettingsNodes(ctx);
17976
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
17977
    DockContextBuildAddWindowsToNodes(ctx, 0);
17978
}
17979
17980
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
17981
{
17982
    if (strcmp(name, "Data") != 0)
17983
        return NULL;
17984
    return (void*)1;
17985
}
17986
17987
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
17988
{
17989
    char c = 0;
17990
    int x = 0, y = 0;
17991
    int r = 0;
17992
17993
    // Parsing, e.g.
17994
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
17995
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
17996
    // Important: this code expect currently fields in a fixed order.
17997
    ImGuiDockNodeSettings node;
17998
    line = ImStrSkipBlank(line);
17999
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
18000
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
18001
    else return;
18002
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
18003
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
18004
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
18005
    if (node.ParentNodeId == 0)
18006
    {
18007
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
18008
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
18009
    }
18010
    else
18011
    {
18012
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
18013
    }
18014
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
18015
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
18016
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
18017
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
18018
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
18019
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
18020
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
18021
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
18022
    if (node.ParentNodeId != 0)
18023
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
18024
            node.Depth = parent_settings->Depth + 1;
18025
    ctx->DockContext.NodesSettings.push_back(node);
18026
}
18027
18028
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
18029
{
18030
    ImGuiDockNodeSettings node_settings;
18031
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
18032
    node_settings.ID = node->ID;
18033
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
18034
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
18035
    node_settings.SelectedTabId = node->SelectedTabId;
18036
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
18037
    node_settings.Depth = (char)depth;
18038
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
18039
    node_settings.Pos = ImVec2ih(node->Pos);
18040
    node_settings.Size = ImVec2ih(node->Size);
18041
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
18042
    dc->NodesSettings.push_back(node_settings);
18043
    if (node->ChildNodes[0])
18044
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
18045
    if (node->ChildNodes[1])
18046
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
18047
}
18048
18049
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
18050
{
18051
    ImGuiContext& g = *ctx;
18052
    ImGuiDockContext* dc = &ctx->DockContext;
18053
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18054
        return;
18055
18056
    // Gather settings data
18057
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
18058
    dc->NodesSettings.resize(0);
18059
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
18060
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18061
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18062
            if (node->IsRootNode())
18063
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
18064
18065
    int max_depth = 0;
18066
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18067
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
18068
18069
    // Write to text buffer
18070
    buf->appendf("[%s][Data]\n", handler->TypeName);
18071
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18072
    {
18073
        const int line_start_pos = buf->size(); (void)line_start_pos;
18074
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
18075
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
18076
        buf->appendf(" ID=0x%08X", node_settings->ID);
18077
        if (node_settings->ParentNodeId)
18078
        {
18079
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
18080
        }
18081
        else
18082
        {
18083
            if (node_settings->ParentWindowId)
18084
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
18085
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
18086
        }
18087
        if (node_settings->SplitAxis != ImGuiAxis_None)
18088
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
18089
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
18090
            buf->appendf(" NoResize=1");
18091
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
18092
            buf->appendf(" CentralNode=1");
18093
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
18094
            buf->appendf(" NoTabBar=1");
18095
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
18096
            buf->appendf(" HiddenTabBar=1");
18097
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
18098
            buf->appendf(" NoWindowMenuButton=1");
18099
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
18100
            buf->appendf(" NoCloseButton=1");
18101
        if (node_settings->SelectedTabId)
18102
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
18103
18104
#if IMGUI_DEBUG_INI_SETTINGS
18105
        // [DEBUG] Include comments in the .ini file to ease debugging
18106
        if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
18107
        {
18108
            buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
18109
            if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
18110
                buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
18111
            // Iterate settings so we can give info about windows that didn't exist during the session.
18112
            int contains_window = 0;
18113
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18114
                if (settings->DockId == node_settings->ID)
18115
                {
18116
                    if (contains_window++ == 0)
18117
                        buf->appendf(" ; contains ");
18118
                    buf->appendf("'%s' ", settings->GetName());
18119
                }
18120
        }
18121
#endif
18122
        buf->appendf("\n");
18123
    }
18124
    buf->appendf("\n");
18125
}
18126
18127
18128
//-----------------------------------------------------------------------------
18129
// [SECTION] PLATFORM DEPENDENT HELPERS
18130
//-----------------------------------------------------------------------------
18131
18132
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
18133
18134
#ifdef _MSC_VER
18135
#pragma comment(lib, "user32")
18136
#pragma comment(lib, "kernel32")
18137
#endif
18138
18139
// Win32 clipboard implementation
18140
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
18141
static const char* GetClipboardTextFn_DefaultImpl(void*)
18142
{
18143
    ImGuiContext& g = *GImGui;
18144
    g.ClipboardHandlerData.clear();
18145
    if (!::OpenClipboard(NULL))
18146
        return NULL;
18147
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
18148
    if (wbuf_handle == NULL)
18149
    {
18150
        ::CloseClipboard();
18151
        return NULL;
18152
    }
18153
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
18154
    {
18155
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
18156
        g.ClipboardHandlerData.resize(buf_len);
18157
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
18158
    }
18159
    ::GlobalUnlock(wbuf_handle);
18160
    ::CloseClipboard();
18161
    return g.ClipboardHandlerData.Data;
18162
}
18163
18164
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18165
{
18166
    if (!::OpenClipboard(NULL))
18167
        return;
18168
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
18169
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
18170
    if (wbuf_handle == NULL)
18171
    {
18172
        ::CloseClipboard();
18173
        return;
18174
    }
18175
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
18176
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
18177
    ::GlobalUnlock(wbuf_handle);
18178
    ::EmptyClipboard();
18179
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
18180
        ::GlobalFree(wbuf_handle);
18181
    ::CloseClipboard();
18182
}
18183
18184
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
18185
18186
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
18187
static PasteboardRef main_clipboard = 0;
18188
18189
// OSX clipboard implementation
18190
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
18191
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18192
{
18193
    if (!main_clipboard)
18194
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18195
    PasteboardClear(main_clipboard);
18196
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
18197
    if (cf_data)
18198
    {
18199
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
18200
        CFRelease(cf_data);
18201
    }
18202
}
18203
18204
static const char* GetClipboardTextFn_DefaultImpl(void*)
18205
{
18206
    if (!main_clipboard)
18207
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18208
    PasteboardSynchronize(main_clipboard);
18209
18210
    ItemCount item_count = 0;
18211
    PasteboardGetItemCount(main_clipboard, &item_count);
18212
    for (ItemCount i = 0; i < item_count; i++)
18213
    {
18214
        PasteboardItemID item_id = 0;
18215
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
18216
        CFArrayRef flavor_type_array = 0;
18217
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
18218
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
18219
        {
18220
            CFDataRef cf_data;
18221
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
18222
            {
18223
                ImGuiContext& g = *GImGui;
18224
                g.ClipboardHandlerData.clear();
18225
                int length = (int)CFDataGetLength(cf_data);
18226
                g.ClipboardHandlerData.resize(length + 1);
18227
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
18228
                g.ClipboardHandlerData[length] = 0;
18229
                CFRelease(cf_data);
18230
                return g.ClipboardHandlerData.Data;
18231
            }
18232
        }
18233
    }
18234
    return NULL;
18235
}
18236
18237
#else
18238
18239
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
18240
static const char* GetClipboardTextFn_DefaultImpl(void*)
18241
{
18242
    ImGuiContext& g = *GImGui;
18243
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
18244
}
18245
18246
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18247
{
18248
    ImGuiContext& g = *GImGui;
18249
    g.ClipboardHandlerData.clear();
18250
    const char* text_end = text + strlen(text);
18251
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
18252
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
18253
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
18254
}
18255
18256
#endif
18257
18258
// Win32 API IME support (for Asian languages, etc.)
18259
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
18260
18261
#include <imm.h>
18262
#ifdef _MSC_VER
18263
#pragma comment(lib, "imm32")
18264
#endif
18265
18266
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
18267
{
18268
    // Notify OS Input Method Editor of text input position
18269
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
18270
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
18271
    if (hwnd == 0)
18272
        hwnd = (HWND)ImGui::GetIO().ImeWindowHandle;
18273
#endif
18274
    if (hwnd == 0)
18275
        return;
18276
18277
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
18278
    if (HIMC himc = ::ImmGetContext(hwnd))
18279
    {
18280
        COMPOSITIONFORM composition_form = {};
18281
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18282
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18283
        composition_form.dwStyle = CFS_FORCE_POSITION;
18284
        ::ImmSetCompositionWindow(himc, &composition_form);
18285
        CANDIDATEFORM candidate_form = {};
18286
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
18287
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18288
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18289
        ::ImmSetCandidateWindow(himc, &candidate_form);
18290
        ::ImmReleaseContext(hwnd, himc);
18291
    }
18292
}
18293
18294
#else
18295
18296
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
18297
18298
#endif
18299
18300
//-----------------------------------------------------------------------------
18301
// [SECTION] METRICS/DEBUGGER WINDOW
18302
//-----------------------------------------------------------------------------
18303
// - RenderViewportThumbnail() [Internal]
18304
// - RenderViewportsThumbnails() [Internal]
18305
// - DebugTextEncoding()
18306
// - MetricsHelpMarker() [Internal]
18307
// - ShowFontAtlas() [Internal]
18308
// - ShowMetricsWindow()
18309
// - DebugNodeColumns() [Internal]
18310
// - DebugNodeDockNode() [Internal]
18311
// - DebugNodeDrawList() [Internal]
18312
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
18313
// - DebugNodeFont() [Internal]
18314
// - DebugNodeFontGlyph() [Internal]
18315
// - DebugNodeStorage() [Internal]
18316
// - DebugNodeTabBar() [Internal]
18317
// - DebugNodeViewport() [Internal]
18318
// - DebugNodeWindow() [Internal]
18319
// - DebugNodeWindowSettings() [Internal]
18320
// - DebugNodeWindowsList() [Internal]
18321
// - DebugNodeWindowsListByBeginStackParent() [Internal]
18322
//-----------------------------------------------------------------------------
18323
18324
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
18325
18326
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
18327
{
18328
    ImGuiContext& g = *GImGui;
18329
    ImGuiWindow* window = g.CurrentWindow;
18330
18331
    ImVec2 scale = bb.GetSize() / viewport->Size;
18332
    ImVec2 off = bb.Min - viewport->Pos * scale;
18333
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_Minimized) ? 0.30f : 1.00f;
18334
    window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
18335
    for (int i = 0; i != g.Windows.Size; i++)
18336
    {
18337
        ImGuiWindow* thumb_window = g.Windows[i];
18338
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
18339
            continue;
18340
        if (thumb_window->Viewport != viewport)
18341
            continue;
18342
18343
        ImRect thumb_r = thumb_window->Rect();
18344
        ImRect title_r = thumb_window->TitleBarRect();
18345
        thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off +  thumb_r.Max * scale));
18346
        title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
18347
        thumb_r.ClipWithFull(bb);
18348
        title_r.ClipWithFull(bb);
18349
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
18350
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
18351
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
18352
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18353
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
18354
    }
18355
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18356
}
18357
18358
static void RenderViewportsThumbnails()
18359
{
18360
    ImGuiContext& g = *GImGui;
18361
    ImGuiWindow* window = g.CurrentWindow;
18362
18363
    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
18364
    float SCALE = 1.0f / 8.0f;
18365
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
18366
    for (int n = 0; n < g.Viewports.Size; n++)
18367
        bb_full.Add(g.Viewports[n]->GetMainRect());
18368
    ImVec2 p = window->DC.CursorPos;
18369
    ImVec2 off = p - bb_full.Min * SCALE;
18370
    for (int n = 0; n < g.Viewports.Size; n++)
18371
    {
18372
        ImGuiViewportP* viewport = g.Viewports[n];
18373
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
18374
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
18375
    }
18376
    ImGui::Dummy(bb_full.GetSize() * SCALE);
18377
}
18378
18379
static int IMGUI_CDECL ViewportComparerByFrontMostStampCount(const void* lhs, const void* rhs)
18380
{
18381
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
18382
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
18383
    return b->LastFrontMostStampCount - a->LastFrontMostStampCount;
18384
}
18385
18386
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
18387
void ImGui::DebugTextEncoding(const char* str)
18388
{
18389
    Text("Text: \"%s\"", str);
18390
    if (!BeginTable("list", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit))
18391
        return;
18392
    TableSetupColumn("Offset");
18393
    TableSetupColumn("UTF-8");
18394
    TableSetupColumn("Glyph");
18395
    TableSetupColumn("Codepoint");
18396
    TableHeadersRow();
18397
    for (const char* p = str; *p != 0; )
18398
    {
18399
        unsigned int c;
18400
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
18401
        TableNextColumn();
18402
        Text("%d", (int)(p - str));
18403
        TableNextColumn();
18404
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
18405
        {
18406
            if (byte_index > 0)
18407
                SameLine();
18408
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
18409
        }
18410
        TableNextColumn();
18411
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
18412
            TextUnformatted(p, p + c_utf8_len);
18413
        else
18414
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
18415
        TableNextColumn();
18416
        Text("U+%04X", (int)c);
18417
        p += c_utf8_len;
18418
    }
18419
    EndTable();
18420
}
18421
18422
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
18423
static void MetricsHelpMarker(const char* desc)
18424
{
18425
    ImGui::TextDisabled("(?)");
18426
    if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort))
18427
    {
18428
        ImGui::BeginTooltip();
18429
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
18430
        ImGui::TextUnformatted(desc);
18431
        ImGui::PopTextWrapPos();
18432
        ImGui::EndTooltip();
18433
    }
18434
}
18435
18436
// [DEBUG] List fonts in a font atlas and display its texture
18437
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
18438
{
18439
    for (int i = 0; i < atlas->Fonts.Size; i++)
18440
    {
18441
        ImFont* font = atlas->Fonts[i];
18442
        PushID(font);
18443
        DebugNodeFont(font);
18444
        PopID();
18445
    }
18446
    if (TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
18447
    {
18448
        ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
18449
        ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f);
18450
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
18451
        TreePop();
18452
    }
18453
}
18454
18455
void ImGui::ShowMetricsWindow(bool* p_open)
18456
{
18457
    ImGuiContext& g = *GImGui;
18458
    ImGuiIO& io = g.IO;
18459
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
18460
    if (cfg->ShowDebugLog)
18461
        ShowDebugLogWindow(&cfg->ShowDebugLog);
18462
    if (cfg->ShowStackTool)
18463
        ShowStackToolWindow(&cfg->ShowStackTool);
18464
18465
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
18466
    {
18467
        End();
18468
        return;
18469
    }
18470
18471
    // Basic info
18472
    Text("Dear ImGui %s", GetVersion());
18473
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
18474
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
18475
    Text("%d visible windows, %d active allocations", io.MetricsRenderWindows, io.MetricsActiveAllocations);
18476
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
18477
18478
    Separator();
18479
18480
    // Debugging enums
18481
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
18482
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
18483
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
18484
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
18485
    if (cfg->ShowWindowsRectsType < 0)
18486
        cfg->ShowWindowsRectsType = WRT_WorkRect;
18487
    if (cfg->ShowTablesRectsType < 0)
18488
        cfg->ShowTablesRectsType = TRT_WorkRect;
18489
18490
    struct Funcs
18491
    {
18492
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
18493
        {
18494
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
18495
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
18496
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
18497
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
18498
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
18499
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
18500
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
18501
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
18502
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
18503
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
18504
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); } // Note: y1/y2 not always accurate
18505
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); }
18506
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); }
18507
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
18508
            IM_ASSERT(0);
18509
            return ImRect();
18510
        }
18511
18512
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
18513
        {
18514
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
18515
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
18516
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
18517
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
18518
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
18519
            else if (rect_type == WRT_Content)       { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
18520
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
18521
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
18522
            IM_ASSERT(0);
18523
            return ImRect();
18524
        }
18525
    };
18526
18527
    // Tools
18528
    if (TreeNode("Tools"))
18529
    {
18530
        bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
18531
        SameLine();
18532
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
18533
        if (show_encoding_viewer)
18534
        {
18535
            static char buf[100] = "";
18536
            SetNextItemWidth(-FLT_MIN);
18537
            InputText("##Text", buf, IM_ARRAYSIZE(buf));
18538
            if (buf[0] != 0)
18539
                DebugTextEncoding(buf);
18540
            TreePop();
18541
        }
18542
18543
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
18544
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
18545
            DebugStartItemPicker();
18546
        SameLine();
18547
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
18548
18549
        // Stack Tool is your best friend!
18550
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
18551
        SameLine();
18552
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
18553
18554
        // Stack Tool is your best friend!
18555
        Checkbox("Show Stack Tool", &cfg->ShowStackTool);
18556
        SameLine();
18557
        MetricsHelpMarker("You can also call ImGui::ShowStackToolWindow() from your code.");
18558
18559
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
18560
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
18561
        SameLine();
18562
        SetNextItemWidth(GetFontSize() * 12);
18563
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
18564
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
18565
        {
18566
            BulletText("'%s':", g.NavWindow->Name);
18567
            Indent();
18568
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
18569
            {
18570
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
18571
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
18572
            }
18573
            Unindent();
18574
        }
18575
18576
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
18577
        SameLine();
18578
        SetNextItemWidth(GetFontSize() * 12);
18579
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
18580
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
18581
        {
18582
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
18583
            {
18584
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
18585
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
18586
                    continue;
18587
18588
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
18589
                if (IsItemHovered())
18590
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
18591
                Indent();
18592
                char buf[128];
18593
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
18594
                {
18595
                    if (rect_n >= TRT_ColumnsRect)
18596
                    {
18597
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
18598
                            continue;
18599
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
18600
                        {
18601
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
18602
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
18603
                            Selectable(buf);
18604
                            if (IsItemHovered())
18605
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
18606
                        }
18607
                    }
18608
                    else
18609
                    {
18610
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
18611
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
18612
                        Selectable(buf);
18613
                        if (IsItemHovered())
18614
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
18615
                    }
18616
                }
18617
                Unindent();
18618
            }
18619
        }
18620
18621
        TreePop();
18622
    }
18623
18624
    // Windows
18625
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
18626
    {
18627
        //SetNextItemOpen(true, ImGuiCond_Once);
18628
        DebugNodeWindowsList(&g.Windows, "By display order");
18629
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
18630
        if (TreeNode("By submission order (begin stack)"))
18631
        {
18632
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
18633
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
18634
            temp_buffer.resize(0);
18635
            for (int i = 0; i < g.Windows.Size; i++)
18636
                if (g.Windows[i]->LastFrameActive + 1 >= g.FrameCount)
18637
                    temp_buffer.push_back(g.Windows[i]);
18638
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
18639
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
18640
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
18641
            TreePop();
18642
        }
18643
18644
        TreePop();
18645
    }
18646
18647
    // DrawLists
18648
    int drawlist_count = 0;
18649
    for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
18650
        drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
18651
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
18652
    {
18653
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
18654
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
18655
        for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
18656
        {
18657
            ImGuiViewportP* viewport = g.Viewports[viewport_i];
18658
            bool viewport_has_drawlist = false;
18659
            for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
18660
                for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
18661
                {
18662
                    if (!viewport_has_drawlist)
18663
                        Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
18664
                    viewport_has_drawlist = true;
18665
                    DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
18666
                }
18667
        }
18668
        TreePop();
18669
    }
18670
18671
    // Viewports
18672
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
18673
    {
18674
        Indent(GetTreeNodeToLabelSpacing());
18675
        RenderViewportsThumbnails();
18676
        Unindent(GetTreeNodeToLabelSpacing());
18677
18678
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
18679
        SameLine();
18680
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
18681
        if (open)
18682
        {
18683
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
18684
            {
18685
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
18686
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
18687
                    i, mon.DpiScale * 100.0f,
18688
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
18689
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
18690
            }
18691
            TreePop();
18692
        }
18693
18694
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
18695
        if (TreeNode("Inferred Z order (front-to-back)"))
18696
        {
18697
            static ImVector<ImGuiViewportP*> viewports;
18698
            viewports.resize(g.Viewports.Size);
18699
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
18700
            if (viewports.Size > 1)
18701
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByFrontMostStampCount);
18702
            for (int i = 0; i < viewports.Size; i++)
18703
                BulletText("Viewport #%d, ID: 0x%08X, FrontMostStampCount = %08d, Window: \"%s\"", viewports[i]->Idx, viewports[i]->ID, viewports[i]->LastFrontMostStampCount, viewports[i]->Window ? viewports[i]->Window->Name : "N/A");
18704
            TreePop();
18705
        }
18706
18707
        for (int i = 0; i < g.Viewports.Size; i++)
18708
            DebugNodeViewport(g.Viewports[i]);
18709
        TreePop();
18710
    }
18711
18712
    // Details for Popups
18713
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
18714
    {
18715
        for (int i = 0; i < g.OpenPopupStack.Size; i++)
18716
        {
18717
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
18718
            const ImGuiPopupData* popup_data = &g.OpenPopupStack[i];
18719
            ImGuiWindow* window = popup_data->Window;
18720
            BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
18721
                popup_data->PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
18722
                popup_data->BackupNavWindow ? popup_data->BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
18723
        }
18724
        TreePop();
18725
    }
18726
18727
    // Details for TabBars
18728
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
18729
    {
18730
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
18731
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
18732
            {
18733
                PushID(tab_bar);
18734
                DebugNodeTabBar(tab_bar, "TabBar");
18735
                PopID();
18736
            }
18737
        TreePop();
18738
    }
18739
18740
    // Details for Tables
18741
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
18742
    {
18743
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
18744
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
18745
                DebugNodeTable(table);
18746
        TreePop();
18747
    }
18748
18749
    // Details for Fonts
18750
    ImFontAtlas* atlas = g.IO.Fonts;
18751
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
18752
    {
18753
        ShowFontAtlas(atlas);
18754
        TreePop();
18755
    }
18756
18757
    // Details for InputText
18758
    if (TreeNode("InputText"))
18759
    {
18760
        DebugNodeInputTextState(&g.InputTextState);
18761
        TreePop();
18762
    }
18763
18764
    // Details for Docking
18765
#ifdef IMGUI_HAS_DOCK
18766
    if (TreeNode("Docking"))
18767
    {
18768
        static bool root_nodes_only = true;
18769
        ImGuiDockContext* dc = &g.DockContext;
18770
        Checkbox("List root nodes", &root_nodes_only);
18771
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
18772
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
18773
        SameLine();
18774
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
18775
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
18776
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18777
                if (!root_nodes_only || node->IsRootNode())
18778
                    DebugNodeDockNode(node, "Node");
18779
        TreePop();
18780
    }
18781
#endif // #ifdef IMGUI_HAS_DOCK
18782
18783
    // Settings
18784
    if (TreeNode("Settings"))
18785
    {
18786
        if (SmallButton("Clear"))
18787
            ClearIniSettings();
18788
        SameLine();
18789
        if (SmallButton("Save to memory"))
18790
            SaveIniSettingsToMemory();
18791
        SameLine();
18792
        if (SmallButton("Save to disk"))
18793
            SaveIniSettingsToDisk(g.IO.IniFilename);
18794
        SameLine();
18795
        if (g.IO.IniFilename)
18796
            Text("\"%s\"", g.IO.IniFilename);
18797
        else
18798
            TextUnformatted("<NULL>");
18799
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
18800
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
18801
        {
18802
            for (int n = 0; n < g.SettingsHandlers.Size; n++)
18803
                BulletText("%s", g.SettingsHandlers[n].TypeName);
18804
            TreePop();
18805
        }
18806
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
18807
        {
18808
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18809
                DebugNodeWindowSettings(settings);
18810
            TreePop();
18811
        }
18812
18813
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
18814
        {
18815
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
18816
                DebugNodeTableSettings(settings);
18817
            TreePop();
18818
        }
18819
18820
#ifdef IMGUI_HAS_DOCK
18821
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
18822
        {
18823
            ImGuiDockContext* dc = &g.DockContext;
18824
            Text("In SettingsWindows:");
18825
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18826
                if (settings->DockId != 0)
18827
                    BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId);
18828
            Text("In SettingsNodes:");
18829
            for (int n = 0; n < dc->NodesSettings.Size; n++)
18830
            {
18831
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
18832
                const char* selected_tab_name = NULL;
18833
                if (settings->SelectedTabId)
18834
                {
18835
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
18836
                        selected_tab_name = window->Name;
18837
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedTabId))
18838
                        selected_tab_name = window_settings->GetName();
18839
                }
18840
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
18841
            }
18842
            TreePop();
18843
        }
18844
#endif // #ifdef IMGUI_HAS_DOCK
18845
18846
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
18847
        {
18848
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
18849
            TreePop();
18850
        }
18851
        TreePop();
18852
    }
18853
18854
    if (TreeNode("Key Owners & Shortcut Routing"))
18855
    {
18856
        TextUnformatted("Key Owners:");
18857
        if (BeginListBox("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8)))
18858
        {
18859
            for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
18860
            {
18861
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
18862
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
18863
                    continue;
18864
                Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
18865
                    owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
18866
                DebugLocateItemOnHover(owner_data->OwnerCurr);
18867
            }
18868
            EndListBox();
18869
        }
18870
        TextUnformatted("Shortcut Routing:");
18871
        if (BeginListBox("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8)))
18872
        {
18873
            for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
18874
            {
18875
                ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
18876
                for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
18877
                {
18878
                    char key_chord_name[64];
18879
                    ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
18880
                    GetKeyChordName(key | routing_data->Mods, key_chord_name, IM_ARRAYSIZE(key_chord_name));
18881
                    Text("%s: 0x%08X", key_chord_name, routing_data->RoutingCurr);
18882
                    DebugLocateItemOnHover(routing_data->RoutingCurr);
18883
                    idx = routing_data->NextEntryIndex;
18884
                }
18885
            }
18886
            EndListBox();
18887
        }
18888
        Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
18889
        TreePop();
18890
    }
18891
18892
    if (TreeNode("Internal state"))
18893
    {
18894
        Text("WINDOWING");
18895
        Indent();
18896
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
18897
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
18898
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
18899
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
18900
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
18901
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
18902
        Unindent();
18903
18904
        Text("ITEMS");
18905
        Indent();
18906
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
18907
        DebugLocateItemOnHover(g.ActiveId);
18908
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
18909
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
18910
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
18911
        Text("HoverDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverDelayId, g.HoverDelayTimer, g.HoverDelayClearTimer);
18912
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
18913
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
18914
        Unindent();
18915
18916
        Text("NAV,FOCUS");
18917
        Indent();
18918
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
18919
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
18920
        DebugLocateItemOnHover(g.NavId);
18921
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
18922
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
18923
        Text("NavActivateId/DownId/PressedId/InputId: %08X/%08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId, g.NavActivateInputId);
18924
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
18925
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
18926
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
18927
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
18928
        Unindent();
18929
18930
        TreePop();
18931
    }
18932
18933
    // Overlay: Display windows Rectangles and Begin Order
18934
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
18935
    {
18936
        for (int n = 0; n < g.Windows.Size; n++)
18937
        {
18938
            ImGuiWindow* window = g.Windows[n];
18939
            if (!window->WasActive)
18940
                continue;
18941
            ImDrawList* draw_list = GetForegroundDrawList(window);
18942
            if (cfg->ShowWindowsRects)
18943
            {
18944
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
18945
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
18946
            }
18947
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
18948
            {
18949
                char buf[32];
18950
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
18951
                float font_size = GetFontSize();
18952
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
18953
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
18954
            }
18955
        }
18956
    }
18957
18958
    // Overlay: Display Tables Rectangles
18959
    if (cfg->ShowTablesRects)
18960
    {
18961
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
18962
        {
18963
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
18964
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
18965
                continue;
18966
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
18967
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
18968
            {
18969
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
18970
                {
18971
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
18972
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
18973
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
18974
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
18975
                }
18976
            }
18977
            else
18978
            {
18979
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
18980
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
18981
            }
18982
        }
18983
    }
18984
18985
#ifdef IMGUI_HAS_DOCK
18986
    // Overlay: Display Docking info
18987
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
18988
    {
18989
        char buf[64] = "";
18990
        char* p = buf;
18991
        ImGuiDockNode* node = g.DebugHoveredDockNode;
18992
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18993
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
18994
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
18995
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
18996
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
18997
        int depth = DockNodeGetDepth(node);
18998
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
18999
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
19000
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
19001
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
19002
    }
19003
#endif // #ifdef IMGUI_HAS_DOCK
19004
19005
    End();
19006
}
19007
19008
// [DEBUG] Display contents of Columns
19009
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
19010
{
19011
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
19012
        return;
19013
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
19014
    for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
19015
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
19016
    TreePop();
19017
}
19018
19019
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
19020
{
19021
    using namespace ImGui;
19022
    PushID(label);
19023
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
19024
    Text("%s:", label);
19025
    if (!enabled)
19026
        BeginDisabled();
19027
    CheckboxFlags("NoSplit", p_flags, ImGuiDockNodeFlags_NoSplit);
19028
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
19029
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
19030
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
19031
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
19032
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
19033
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
19034
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
19035
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking);
19036
    CheckboxFlags("NoDockingSplitMe", p_flags, ImGuiDockNodeFlags_NoDockingSplitMe);
19037
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
19038
    CheckboxFlags("NoDockingOverMe", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
19039
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
19040
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
19041
    if (!enabled)
19042
        EndDisabled();
19043
    PopStyleVar();
19044
    PopID();
19045
}
19046
19047
// [DEBUG] Display contents of ImDockNode
19048
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
19049
{
19050
    ImGuiContext& g = *GImGui;
19051
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
19052
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
19053
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19054
    bool open;
19055
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19056
    if (node->Windows.Size > 0)
19057
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19058
    else
19059
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19060
    if (!is_alive) { PopStyleColor(); }
19061
    if (is_active && IsItemHovered())
19062
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
19063
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
19064
    if (open)
19065
    {
19066
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
19067
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
19068
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
19069
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
19070
        DebugNodeWindow(node->HostWindow, "HostWindow");
19071
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
19072
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
19073
        BulletText("Misc:%s%s%s%s%s%s%s",
19074
            node->IsDockSpace() ? " IsDockSpace" : "",
19075
            node->IsCentralNode() ? " IsCentralNode" : "",
19076
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
19077
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
19078
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
19079
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
19080
        {
19081
            if (BeginTable("flags", 4))
19082
            {
19083
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
19084
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
19085
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
19086
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
19087
                EndTable();
19088
            }
19089
            TreePop();
19090
        }
19091
        if (node->ParentNode)
19092
            DebugNodeDockNode(node->ParentNode, "ParentNode");
19093
        if (node->ChildNodes[0])
19094
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
19095
        if (node->ChildNodes[1])
19096
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
19097
        if (node->TabBar)
19098
            DebugNodeTabBar(node->TabBar, "TabBar");
19099
        DebugNodeWindowsList(&node->Windows, "Windows");
19100
19101
        TreePop();
19102
    }
19103
}
19104
19105
// [DEBUG] Display contents of ImDrawList
19106
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
19107
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
19108
{
19109
    ImGuiContext& g = *GImGui;
19110
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19111
    int cmd_count = draw_list->CmdBuffer.Size;
19112
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
19113
        cmd_count--;
19114
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
19115
    if (draw_list == GetWindowDrawList())
19116
    {
19117
        SameLine();
19118
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
19119
        if (node_open)
19120
            TreePop();
19121
        return;
19122
    }
19123
19124
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
19125
    if (window && IsItemHovered() && fg_draw_list)
19126
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19127
    if (!node_open)
19128
        return;
19129
19130
    if (window && !window->WasActive)
19131
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
19132
19133
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
19134
    {
19135
        if (pcmd->UserCallback)
19136
        {
19137
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
19138
            continue;
19139
        }
19140
19141
        char buf[300];
19142
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
19143
            pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
19144
            pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
19145
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
19146
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
19147
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
19148
        if (!pcmd_node_open)
19149
            continue;
19150
19151
        // Calculate approximate coverage area (touched pixel count)
19152
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
19153
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
19154
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
19155
        float total_area = 0.0f;
19156
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
19157
        {
19158
            ImVec2 triangle[3];
19159
            for (int n = 0; n < 3; n++, idx_n++)
19160
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
19161
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
19162
        }
19163
19164
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
19165
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
19166
        Selectable(buf);
19167
        if (IsItemHovered() && fg_draw_list)
19168
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
19169
19170
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
19171
        ImGuiListClipper clipper;
19172
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
19173
        while (clipper.Step())
19174
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
19175
            {
19176
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
19177
                ImVec2 triangle[3];
19178
                for (int n = 0; n < 3; n++, idx_i++)
19179
                {
19180
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
19181
                    triangle[n] = v.pos;
19182
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
19183
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
19184
                }
19185
19186
                Selectable(buf, false);
19187
                if (fg_draw_list && IsItemHovered())
19188
                {
19189
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
19190
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19191
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
19192
                    fg_draw_list->Flags = backup_flags;
19193
                }
19194
            }
19195
        TreePop();
19196
    }
19197
    TreePop();
19198
}
19199
19200
// [DEBUG] Display mesh/aabb of a ImDrawCmd
19201
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
19202
{
19203
    IM_ASSERT(show_mesh || show_aabb);
19204
19205
    // Draw wire-frame version of all triangles
19206
    ImRect clip_rect = draw_cmd->ClipRect;
19207
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19208
    ImDrawListFlags backup_flags = out_draw_list->Flags;
19209
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19210
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
19211
    {
19212
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
19213
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
19214
19215
        ImVec2 triangle[3];
19216
        for (int n = 0; n < 3; n++, idx_n++)
19217
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
19218
        if (show_mesh)
19219
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
19220
    }
19221
    // Draw bounding boxes
19222
    if (show_aabb)
19223
    {
19224
        out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
19225
        out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
19226
    }
19227
    out_draw_list->Flags = backup_flags;
19228
}
19229
19230
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
19231
void ImGui::DebugNodeFont(ImFont* font)
19232
{
19233
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
19234
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
19235
    SameLine();
19236
    if (SmallButton("Set as default"))
19237
        GetIO().FontDefault = font;
19238
    if (!opened)
19239
        return;
19240
19241
    // Display preview text
19242
    PushFont(font);
19243
    Text("The quick brown fox jumps over the lazy dog");
19244
    PopFont();
19245
19246
    // Display details
19247
    SetNextItemWidth(GetFontSize() * 8);
19248
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
19249
    SameLine(); MetricsHelpMarker(
19250
        "Note than the default embedded font is NOT meant to be scaled.\n\n"
19251
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
19252
        "You may oversample them to get some flexibility with scaling. "
19253
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
19254
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
19255
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
19256
    char c_str[5];
19257
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
19258
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
19259
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
19260
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
19261
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
19262
        if (font->ConfigData)
19263
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
19264
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
19265
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
19266
19267
    // Display all glyphs of the fonts in separate pages of 256 characters
19268
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
19269
    {
19270
        ImDrawList* draw_list = GetWindowDrawList();
19271
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
19272
        const float cell_size = font->FontSize * 1;
19273
        const float cell_spacing = GetStyle().ItemSpacing.y;
19274
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
19275
        {
19276
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
19277
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
19278
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
19279
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
19280
            {
19281
                base += 4096 - 256;
19282
                continue;
19283
            }
19284
19285
            int count = 0;
19286
            for (unsigned int n = 0; n < 256; n++)
19287
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
19288
                    count++;
19289
            if (count <= 0)
19290
                continue;
19291
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
19292
                continue;
19293
19294
            // Draw a 16x16 grid of glyphs
19295
            ImVec2 base_pos = GetCursorScreenPos();
19296
            for (unsigned int n = 0; n < 256; n++)
19297
            {
19298
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
19299
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
19300
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
19301
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
19302
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
19303
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
19304
                if (!glyph)
19305
                    continue;
19306
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
19307
                if (IsMouseHoveringRect(cell_p1, cell_p2))
19308
                {
19309
                    BeginTooltip();
19310
                    DebugNodeFontGlyph(font, glyph);
19311
                    EndTooltip();
19312
                }
19313
            }
19314
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
19315
            TreePop();
19316
        }
19317
        TreePop();
19318
    }
19319
    TreePop();
19320
}
19321
19322
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
19323
{
19324
    Text("Codepoint: U+%04X", glyph->Codepoint);
19325
    Separator();
19326
    Text("Visible: %d", glyph->Visible);
19327
    Text("AdvanceX: %.1f", glyph->AdvanceX);
19328
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
19329
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
19330
}
19331
19332
// [DEBUG] Display contents of ImGuiStorage
19333
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
19334
{
19335
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
19336
        return;
19337
    for (int n = 0; n < storage->Data.Size; n++)
19338
    {
19339
        const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
19340
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
19341
    }
19342
    TreePop();
19343
}
19344
19345
// [DEBUG] Display contents of ImGuiTabBar
19346
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
19347
{
19348
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
19349
    char buf[256];
19350
    char* p = buf;
19351
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
19352
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
19353
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
19354
    p += ImFormatString(p, buf_end - p, "  { ");
19355
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
19356
    {
19357
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19358
        p += ImFormatString(p, buf_end - p, "%s'%s'",
19359
            tab_n > 0 ? ", " : "", (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???");
19360
    }
19361
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
19362
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19363
    bool open = TreeNode(label, "%s", buf);
19364
    if (!is_active) { PopStyleColor(); }
19365
    if (is_active && IsItemHovered())
19366
    {
19367
        ImDrawList* draw_list = GetForegroundDrawList();
19368
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
19369
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
19370
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
19371
    }
19372
    if (open)
19373
    {
19374
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
19375
        {
19376
            const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19377
            PushID(tab);
19378
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
19379
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
19380
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
19381
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???", tab->Offset, tab->Width, tab->ContentWidth);
19382
            PopID();
19383
        }
19384
        TreePop();
19385
    }
19386
}
19387
19388
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
19389
{
19390
    SetNextItemOpen(true, ImGuiCond_Once);
19391
    if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
19392
    {
19393
        ImGuiWindowFlags flags = viewport->Flags;
19394
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
19395
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
19396
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
19397
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
19398
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
19399
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
19400
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
19401
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
19402
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
19403
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
19404
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
19405
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
19406
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
19407
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
19408
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
19409
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
19410
            (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : "",
19411
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
19412
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
19413
        for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
19414
            for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
19415
                DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
19416
        TreePop();
19417
    }
19418
}
19419
19420
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
19421
{
19422
    if (window == NULL)
19423
    {
19424
        BulletText("%s: NULL", label);
19425
        return;
19426
    }
19427
19428
    ImGuiContext& g = *GImGui;
19429
    const bool is_active = window->WasActive;
19430
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19431
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19432
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
19433
    if (!is_active) { PopStyleColor(); }
19434
    if (IsItemHovered() && is_active)
19435
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19436
    if (!open)
19437
        return;
19438
19439
    if (window->MemoryCompacted)
19440
        TextDisabled("Note: some memory buffers have been compacted/freed.");
19441
19442
    ImGuiWindowFlags flags = window->Flags;
19443
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
19444
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
19445
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
19446
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
19447
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
19448
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
19449
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
19450
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
19451
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
19452
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
19453
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
19454
    {
19455
        ImRect r = window->NavRectRel[layer];
19456
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
19457
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
19458
        else
19459
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
19460
        DebugLocateItemOnHover(window->NavLastIds[layer]);
19461
    }
19462
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
19463
19464
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
19465
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
19466
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
19467
    if (window->DockNode || window->DockNodeAsHost)
19468
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
19469
19470
    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
19471
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
19472
    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
19473
    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
19474
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
19475
    {
19476
        for (int n = 0; n < window->ColumnsStorage.Size; n++)
19477
            DebugNodeColumns(&window->ColumnsStorage[n]);
19478
        TreePop();
19479
    }
19480
    DebugNodeStorage(&window->StateStorage, "Storage");
19481
    TreePop();
19482
}
19483
19484
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
19485
{
19486
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
19487
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
19488
}
19489
19490
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
19491
{
19492
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
19493
        return;
19494
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
19495
    {
19496
        PushID((*windows)[i]);
19497
        DebugNodeWindow((*windows)[i], "Window");
19498
        PopID();
19499
    }
19500
    TreePop();
19501
}
19502
19503
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
19504
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
19505
{
19506
    for (int i = 0; i < windows_size; i++)
19507
    {
19508
        ImGuiWindow* window = windows[i];
19509
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
19510
            continue;
19511
        char buf[20];
19512
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
19513
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
19514
        DebugNodeWindow(window, buf);
19515
        Indent();
19516
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
19517
        Unindent();
19518
    }
19519
}
19520
19521
//-----------------------------------------------------------------------------
19522
// [SECTION] DEBUG LOG WINDOW
19523
//-----------------------------------------------------------------------------
19524
19525
void ImGui::DebugLog(const char* fmt, ...)
19526
{
19527
    va_list args;
19528
    va_start(args, fmt);
19529
    DebugLogV(fmt, args);
19530
    va_end(args);
19531
}
19532
19533
void ImGui::DebugLogV(const char* fmt, va_list args)
19534
{
19535
    ImGuiContext& g = *GImGui;
19536
    const int old_size = g.DebugLogBuf.size();
19537
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
19538
    g.DebugLogBuf.appendfv(fmt, args);
19539
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
19540
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
19541
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
19542
}
19543
19544
void ImGui::ShowDebugLogWindow(bool* p_open)
19545
{
19546
    ImGuiContext& g = *GImGui;
19547
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
19548
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
19549
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
19550
    {
19551
        End();
19552
        return;
19553
    }
19554
19555
    AlignTextToFramePadding();
19556
    Text("Log events:");
19557
    SameLine(); CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
19558
    SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
19559
    SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
19560
    SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
19561
    SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
19562
    SameLine(); CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper);
19563
    SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
19564
    SameLine(); CheckboxFlags("Docking", &g.DebugLogFlags, ImGuiDebugLogFlags_EventDocking);
19565
    SameLine(); CheckboxFlags("Viewport", &g.DebugLogFlags, ImGuiDebugLogFlags_EventViewport);
19566
19567
    if (SmallButton("Clear"))
19568
    {
19569
        g.DebugLogBuf.clear();
19570
        g.DebugLogIndex.clear();
19571
    }
19572
    SameLine();
19573
    if (SmallButton("Copy"))
19574
        SetClipboardText(g.DebugLogBuf.c_str());
19575
    BeginChild("##log", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
19576
19577
    ImGuiListClipper clipper;
19578
    clipper.Begin(g.DebugLogIndex.size());
19579
    while (clipper.Step())
19580
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
19581
        {
19582
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
19583
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
19584
            TextUnformatted(line_begin, line_end);
19585
            ImRect text_rect = g.LastItemData.Rect;
19586
            if (IsItemHovered())
19587
                for (const char* p = line_begin; p < line_end - 10; p++)
19588
                {
19589
                    ImGuiID id = 0;
19590
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
19591
                        continue;
19592
                    ImVec2 p0 = CalcTextSize(line_begin, p);
19593
                    ImVec2 p1 = CalcTextSize(p, p + 10);
19594
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
19595
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
19596
                        DebugLocateItemOnHover(id);
19597
                    p += 10;
19598
                }
19599
        }
19600
    if (GetScrollY() >= GetScrollMaxY())
19601
        SetScrollHereY(1.0f);
19602
    EndChild();
19603
19604
    End();
19605
}
19606
19607
//-----------------------------------------------------------------------------
19608
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
19609
//-----------------------------------------------------------------------------
19610
19611
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
19612
19613
void ImGui::DebugLocateItem(ImGuiID target_id)
19614
{
19615
    ImGuiContext& g = *GImGui;
19616
    g.DebugLocateId = target_id;
19617
    g.DebugLocateFrames = 2;
19618
}
19619
19620
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
19621
{
19622
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
19623
        return;
19624
    ImGuiContext& g = *GImGui;
19625
    DebugLocateItem(target_id);
19626
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
19627
}
19628
19629
void ImGui::DebugLocateItemResolveWithLastItem()
19630
{
19631
    ImGuiContext& g = *GImGui;
19632
    ImGuiLastItemData item_data = g.LastItemData;
19633
    g.DebugLocateId = 0;
19634
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
19635
    ImRect r = item_data.Rect;
19636
    r.Expand(3.0f);
19637
    ImVec2 p1 = g.IO.MousePos;
19638
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
19639
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
19640
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
19641
}
19642
19643
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
19644
void ImGui::UpdateDebugToolItemPicker()
19645
{
19646
    ImGuiContext& g = *GImGui;
19647
    g.DebugItemPickerBreakId = 0;
19648
    if (!g.DebugItemPickerActive)
19649
        return;
19650
19651
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
19652
    SetMouseCursor(ImGuiMouseCursor_Hand);
19653
    if (IsKeyPressed(ImGuiKey_Escape))
19654
        g.DebugItemPickerActive = false;
19655
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
19656
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
19657
    {
19658
        g.DebugItemPickerBreakId = hovered_id;
19659
        g.DebugItemPickerActive = false;
19660
    }
19661
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
19662
        if (change_mapping && IsMouseClicked(mouse_button))
19663
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
19664
    SetNextWindowBgAlpha(0.70f);
19665
    BeginTooltip();
19666
    Text("HoveredId: 0x%08X", hovered_id);
19667
    Text("Press ESC to abort picking.");
19668
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
19669
    if (change_mapping)
19670
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
19671
    else
19672
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
19673
    EndTooltip();
19674
}
19675
19676
// [DEBUG] Stack Tool: update queries. Called by NewFrame()
19677
void ImGui::UpdateDebugToolStackQueries()
19678
{
19679
    ImGuiContext& g = *GImGui;
19680
    ImGuiStackTool* tool = &g.DebugStackTool;
19681
19682
    // Clear hook when stack tool is not visible
19683
    g.DebugHookIdInfo = 0;
19684
    if (g.FrameCount != tool->LastActiveFrame + 1)
19685
        return;
19686
19687
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
19688
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
19689
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
19690
    if (tool->QueryId != query_id)
19691
    {
19692
        tool->QueryId = query_id;
19693
        tool->StackLevel = -1;
19694
        tool->Results.resize(0);
19695
    }
19696
    if (query_id == 0)
19697
        return;
19698
19699
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
19700
    int stack_level = tool->StackLevel;
19701
    if (stack_level >= 0 && stack_level < tool->Results.Size)
19702
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
19703
            tool->StackLevel++;
19704
19705
    // Update hook
19706
    stack_level = tool->StackLevel;
19707
    if (stack_level == -1)
19708
        g.DebugHookIdInfo = query_id;
19709
    if (stack_level >= 0 && stack_level < tool->Results.Size)
19710
    {
19711
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
19712
        tool->Results[stack_level].QueryFrameCount++;
19713
    }
19714
}
19715
19716
// [DEBUG] Stack tool: hooks called by GetID() family functions
19717
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
19718
{
19719
    ImGuiContext& g = *GImGui;
19720
    ImGuiWindow* window = g.CurrentWindow;
19721
    ImGuiStackTool* tool = &g.DebugStackTool;
19722
19723
    // Step 0: stack query
19724
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
19725
    if (tool->StackLevel == -1)
19726
    {
19727
        tool->StackLevel++;
19728
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
19729
        for (int n = 0; n < window->IDStack.Size + 1; n++)
19730
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
19731
        return;
19732
    }
19733
19734
    // Step 1+: query for individual level
19735
    IM_ASSERT(tool->StackLevel >= 0);
19736
    if (tool->StackLevel != window->IDStack.Size)
19737
        return;
19738
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
19739
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
19740
19741
    switch (data_type)
19742
    {
19743
    case ImGuiDataType_S32:
19744
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
19745
        break;
19746
    case ImGuiDataType_String:
19747
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
19748
        break;
19749
    case ImGuiDataType_Pointer:
19750
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
19751
        break;
19752
    case ImGuiDataType_ID:
19753
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
19754
            return;
19755
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
19756
        break;
19757
    default:
19758
        IM_ASSERT(0);
19759
    }
19760
    info->QuerySuccess = true;
19761
    info->DataType = data_type;
19762
}
19763
19764
static int StackToolFormatLevelInfo(ImGuiStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
19765
{
19766
    ImGuiStackLevelInfo* info = &tool->Results[n];
19767
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
19768
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
19769
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
19770
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
19771
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
19772
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
19773
        return (*buf = 0);
19774
#ifdef IMGUI_ENABLE_TEST_ENGINE
19775
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
19776
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
19777
#endif
19778
    return ImFormatString(buf, buf_size, "???");
19779
}
19780
19781
// Stack Tool: Display UI
19782
void ImGui::ShowStackToolWindow(bool* p_open)
19783
{
19784
    ImGuiContext& g = *GImGui;
19785
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
19786
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
19787
    if (!Begin("Dear ImGui Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
19788
    {
19789
        End();
19790
        return;
19791
    }
19792
19793
    // Display hovered/active status
19794
    ImGuiStackTool* tool = &g.DebugStackTool;
19795
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
19796
    const ImGuiID active_id = g.ActiveId;
19797
#ifdef IMGUI_ENABLE_TEST_ENGINE
19798
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
19799
#else
19800
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
19801
#endif
19802
    SameLine();
19803
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
19804
19805
    // CTRL+C to copy path
19806
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
19807
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
19808
    SameLine();
19809
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
19810
    if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
19811
    {
19812
        tool->CopyToClipboardLastTime = (float)g.Time;
19813
        char* p = g.TempBuffer.Data;
19814
        char* p_end = p + g.TempBuffer.Size;
19815
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
19816
        {
19817
            *p++ = '/';
19818
            char level_desc[256];
19819
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
19820
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
19821
            {
19822
                if (level_desc[n] == '/')
19823
                    *p++ = '\\';
19824
                *p++ = level_desc[n];
19825
            }
19826
        }
19827
        *p = '\0';
19828
        SetClipboardText(g.TempBuffer.Data);
19829
    }
19830
19831
    // Display decorated stack
19832
    tool->LastActiveFrame = g.FrameCount;
19833
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
19834
    {
19835
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
19836
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
19837
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
19838
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
19839
        TableHeadersRow();
19840
        for (int n = 0; n < tool->Results.Size; n++)
19841
        {
19842
            ImGuiStackLevelInfo* info = &tool->Results[n];
19843
            TableNextColumn();
19844
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
19845
            TableNextColumn();
19846
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
19847
            TextUnformatted(g.TempBuffer.Data);
19848
            TableNextColumn();
19849
            Text("0x%08X", info->ID);
19850
            if (n == tool->Results.Size - 1)
19851
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
19852
        }
19853
        EndTable();
19854
    }
19855
    End();
19856
}
19857
19858
#else
19859
19860
void ImGui::ShowMetricsWindow(bool*) {}
19861
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
19862
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
19863
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
19864
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
19865
void ImGui::DebugNodeFont(ImFont*) {}
19866
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
19867
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
19868
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
19869
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
19870
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
19871
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
19872
19873
void ImGui::DebugLog(const char*, ...) {}
19874
void ImGui::DebugLogV(const char*, va_list) {}
19875
void ImGui::ShowDebugLogWindow(bool*) {}
19876
void ImGui::ShowStackToolWindow(bool*) {}
19877
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
19878
void ImGui::UpdateDebugToolItemPicker() {}
19879
void ImGui::UpdateDebugToolStackQueries() {}
19880
19881
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
19882
19883
//-----------------------------------------------------------------------------
19884
19885
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
19886
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
19887
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
19888
#include "imgui_user.inl"
19889
#endif
19890
19891
//-----------------------------------------------------------------------------
19892
19893
#endif // #ifndef IMGUI_DISABLE